MATLAB: Can we vectorize this kind of for loop

dependencyfor loopMATLABspeed upvectorization

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!

Best Answer

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