changing dimension in a loop

1 Ansicht (letzte 30 Tage)
Rafael Schwarzenegger
Rafael Schwarzenegger am 3 Okt. 2018
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

Akzeptierte Antwort

Stephen23
Stephen23 am 3 Okt. 2018
Bearbeitet: Stephen23 am 3 Okt. 2018
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.

Weitere Antworten (0)

Kategorien

Mehr zu Matrix Indexing 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!

Translated by