changing dimension in a loop
3 views (last 30 days)
Show older comments
Rafael Schwarzenegger
on 3 Oct 2018
Commented: Rafael Schwarzenegger
on 3 Oct 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
0 Comments
Accepted Answer
Stephen23
on 3 Oct 2018
Edited: Stephen23
on 3 Oct 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.
More Answers (0)
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!