Can we vectorize this kind of for loop?

The for loop is as follows:
N=2;T=3;
Trials=rand(N,T);
for i=1:N
for j=1:T
AverageValue=mean2(Trials);
Trials(i,j)=Trials(i,j)-AverageValue;
end
end
The difficult is that 'AverageValue' changes its value according to each updated 'Trials'.
===========================================
Updated version with 'mean2' replaced by 'trapz':
N=4;T=5;
Trials=rand(N,T);
for i=1:N
for j=1:T
IntValue=trapz(trapz(Trials(1:3,2:5)));
Trials(i,j)=Trials(i,j)+IntValue;
end
end
Please help, thank you!

 Accepted Answer

Matt J
Matt J on 18 Apr 2013
Edited: Matt J on 19 Apr 2013
I agree with Sean's general point, that for-loops needn't be vectorized at all costs. However, you can make this particular for-loop much more efficient (for large N and T) by incrementally updating AverageValue:
N=2;T=3;
Trials=rand(N,T);
AverageValue=mean2(Trials);
coeff=1-1/N/T;
for i=1:N
for j=1:T
Trials(i,j)=Trials(i,j)-AverageValue;
AverageValue=AverageValue*coeff;
end
end

5 Comments

And therefore, I guess you could vectorize it as follows
Averages=mean2(Trials)*reshape(coeff.^(0:N*T-1),T,N).';
Trials = Trials - Averages;
Thank Matt J so much for your answer. It works. I would like to know if this principle can be applied for other function than mean2, e.g., an integral function of 'Trials'?
Matt J
Matt J on 18 Apr 2013
Edited: Matt J on 18 Apr 2013
It should be readily applicable to any linear operation, which mean2 is. It might also be applicable to some non-linear operations if the response to a change in one Trial(i,j) has a simple incremental effect on the output. That would have to be considered on a case-by-case basis, though.
Thank Matt J for your reply. As commented by Jan, I have updated the more complicated code by replacing 'mean2' by 'trapz'. Could you please help me to vectorize it. Thank again.
I would have to see how trapz is being used. In the meantime, please Accept-click my answer, since it seems to fulfill your posted question.

Sign in to comment.

More Answers (1)

I wouldn't bother vectorizing this.

3 Comments

Thank Sean! I agree that for loop is not bad. However, for my code (it is not the simple code that I wrote above), for loop really takes time. This is why I seek a vectorized version ... Thank!
@Tuan: Do not post simplified versions of the code, when you ask for an optimization. Then important details are missing.
Dear Jan, I have updated the more complicated code by replacing 'mean2' by 'trapz'. I hope to receive your help. Thank you.

Sign in to comment.

Products

Asked:

on 18 Apr 2013

Community Treasure Hunt

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

Start Hunting!