MATLAB: Changing dimension in a loop

dimensionfor looploopMATLABMATLAB and Simulink Student Suite

Hello,
I would like to be changing the dimension in a loop. In other words, I would like to re-write this code in a single loop
e1=mean(reshape(A(:,1,:,:,:),1,[]));
e2=mean(reshape(A(:,2,:,:,:),1,[]));
e3=mean(reshape(A(:,3,:,:,:),1,[]));
vp=var([e1 e2 e3]);
s(1) = vp/v;
e1=mean(reshape(A(:,:,1,:,:),1,[]));
e2=mean(reshape(A(:,:,2,:,:),1,[]));
e3=mean(reshape(A(:,:,3,:,:),1,[]));
vp=var([e1 e2 e3]);
s(2) = vp/v;
So that I have for i=1:2 an expression for s(i).
Thank you.
Best,
Rafael

Best Answer

There is a neat trick for that: simply put the indices into a cell array, which you can then redefine using indexing.
S = nan(1,2);
for k = 1:2
C = {':',':',':',':',':'};
C{1+k} = 1;
e1 = mean(reshape(A(C{:}),1,[]));
C{1+k} = 2;
e2 = mean(reshape(A(C{:}),1,[]));
C{1+k} = 3;
e3 = mean(reshape(A(C{:}),1,[]));
vp = var([e1,e2,e3]);
S(k) = vp/v;
end
This uses the power of a comma-separated list, which are very useful in lots of situations:
Probably you could even get rid of the repeated lines of code, with appropriate permute, reshape, and mean calls.