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 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Sterre
am 31 Mär. 2019
Beantwortet: Andrei Bobrov
am 31 Mär. 2019
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 Kommentare
Akzeptierte Antwort
Andrei Bobrov
am 31 Mär. 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);
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!