Problem with a for loop

3 ビュー (過去 30 日間)
JD
JD 2013 年 7 月 3 日
Hello,
I have a four-dimensional matrix A(i,o,h,j) and I would like to find the mean of each j for each i,o,h. My goal is to get a tree-dimensional matrix B(i,o,h).
For example:
B(1,1,1)=(A(1,1,1,1)+A(1,1,1,2)+...+A(1,1,1,9))./9
B(150,12,7)=(A(150,12,7,1)+A(150,12,7,2)+...+A(150,12,7,9))./9
However this code below gives me a two 160x1 matrix. Any help would be much appreciated!
l=160;
h=1;
o=1;
i=1;
for h=1:12
for o=1:12
for i=i:l-o-h
B(i,o,h)=mean(A(i,o,h,:));
i=i+1;
end
o=o+1;
end
h=h+1;
end

回答 (2 件)

Jonathan Sullivan
Jonathan Sullivan 2013 年 7 月 3 日
It's much easier than this. The function mean allows you to specify a dimension over which to operate.
For you, you would want:
B = mean(A,4);
For more information, look at the documentation
help mean
doc mean

Kevin
Kevin 2013 年 7 月 3 日
編集済み: Kevin 2013 年 7 月 3 日
for h=1:size(A,3)
for o=1:size(A,2)
for i=1:size(A,1)
B(i,o,h)=mean(A(i,o,h,:),4);
% (1) deleted your step fxn, matlab does this auto-magically
end
% (2) same as (1)
end
% (3) same as (1)
end
This is the same effect as Jonathan's answer, but implemented as your for loop. Best of luck. KD
EDIT: For the record, Jon's is the way to do it...

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by