How to form a for-loop to: find the onset (first element) of trials of zeros, ones and twos, in an array of sequences of zeros, ones and twos

3 vues (au cours des 30 derniers jours)
I am trying to make a function (with a for-loop in it) that finds the onsets of (three different) trials (in this case, the trial starts when a new sequence of zeros, ones and twos starts in an array of numbers, this array of numbers always consists of sequences of ones, zeros and twos).
See the example of such an array (E) for a clarification:
E = [zeros(1,10) ones(1,5) zeros(1,8) 2*ones(1,4) zeros(1,12)]
This array is always a rowvector. The example consists of 5 trials, and 39 elements (10+5+8+4+12).
With the funtion, I want to find the elements (1:39) of the starts of every trial: [start_of_trial], with the corresponding value 0, 1 or 2: [trial_value]. This way, the function will be as follows:
function [start_of_trial, trial_value] = find_onsets(E)
start_of_trial = find([1;diff(E(:))~= 0]);
trial_value = E(start_of_trial);
end
Now, although it is not necessary, I have to make a for-loop to find the same output, instead of the function above.
How can I make a for-loop with this function? I tried several things, but I am stuck with how to use the for-loop properly in this case
  8 commentaires
Sterre
Sterre le 31 Mar 2019
Here, my revised code:
function [start_of_trial, trial_value] = find_onsets_loop(E)
counter = 1;
a = 5;
start_of_trial = zeros(a);
trial_value = zeros(a);
for i = 2:length(E)
if E(i) ~= E(i-1)
start_of_trial(counter) = i;
trial_value(counter) = E(i-1);
i = 0;
counter = counter + 1;
else
i = i + 1;
end
end

Connectez-vous pour commenter.

Réponse acceptée

Andrei Bobrov
Andrei Bobrov le 31 Mar 2019
n = numel(E);
count1 = 1;
start_of_trial = [1;zeros(n-1,1)];
trial_value = zeros(n,1);
for ii = 2:n
if E(ii) - E(ii-1) ~= 0
count1 = count1 + 1;
start_of_trial(count1) = ii;
trial_value(count1) = E(ii);
end
end
start_of_trial = start_of_trial(1:count1);
trial_value = trial_value(1:count1);

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by