changing dimension in a loop

1 回表示 (過去 30 日間)
Rafael Schwarzenegger
Rafael Schwarzenegger 2018 年 10 月 3 日
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.
  1 件のコメント
Rafael Schwarzenegger
Rafael Schwarzenegger 2018 年 10 月 3 日
Works excellent, thank you!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by