speed optimization in "for" loops

Hi,
I have an experiment with 864 trials. I have an array named Edf_Trials3, with data of saccadic eye movements during the entire experiment. In some trials I have more than one eye movement, in others there is none.
I have an other array, named Time_EndPpt6, with the time of the stimuli presentation in each trial.
I would like to add the time of the stimuli presentation in the former array "Edf_Trials3", on the same line of the corresponding trial.
For that i'm using 2 loops but it's very very long.
Could you help to simplify my code in order to boost the process ?
I add the two arrays. this is my code:
for (j=1:height(Edf_Trials3))
for(i=1:length(Time_EndPpt6))
if (Edf_Trials3.Trial(j)==i)
Edf_Trials3.EndTime_of_Ppt(j)=Time_EndPpt6(i);
end
end
end
Thanks for your help

1 Comment

I'd omit the strange parentheses for the for and if commands. It works, but does not look Matlabish.

Sign in to comment.

 Accepted Answer

Jan
Jan on 24 Oct 2018
Edited: Jan on 24 Oct 2018
The code overwrites Edf_Trials3.EndTime_of_Ppt(j) repeatedly. Then you can run the inner loop in backward direction and stop at the first match:
% [EDITED] pre-allocation
Edf_Trials3.EndTime_of_Ppt = zeros(1, height(Edf_Trials3));
for j = 1:height(Edf_Trials3)
for i = length(Time_EndPpt6):-1:1
if Edf_Trials3.Trial(j) == i
Edf_Trials3.EndTime_of_Ppt(j) = Time_EndPpt6(i);
break; % Stop "for i" loop early
end
end
end
You could try a vectorization also:
% [EDITED] pre-allocation, typo: "m" -> "idx"
tmp = zeros(1, height(Edf_Trials3));
v = 1:length(Time_EndPpt6);
for j = 1:height(Edf_Trials3)
idx = find(Edf_Trials3.Trial(j) == v, 1, 'last');
tmp(j) = Time_EndPpt6(idx);
end
Edf_Trials3.EndTime_of_Ppt = tmp;
How large are the inputs? Can you post some relevant small example data?

3 Comments

Thanks for your answer,
In attachment you will find the examples of tables that I use. The array Time_EndPpt6 is 1x864 double array and the Edf_Trials3 is approximately 2 000 000 x9 table.
Jan
Jan on 24 Oct 2018
Edited: Jan on 24 Oct 2018
Unfortunately I cannot open MAT files currently, because I do not have access to Matlab. Is Edf_Trials3.EndTime_of_Ppt pre-allocated? If not, see my edited code. Is Edf_Trials3.Trial sorted? Do my suggests decrease the run-time already?
It's perfectly working now. Thanks a lot !

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!