Problem with a for loop
1 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
回答(2 个)
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
0 个评论
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...
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!