Problem with a for loop

조회 수: 1 (최근 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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by