changing dimension in a loop

1 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2018-10-3
编辑:Stephen23 2018-10-3
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by