# Problem with a for loop

3 Ansichten (letzte 30 Tage)
JD am 3 Jul. 2013
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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (2)

Jonathan Sullivan am 3 Jul. 2013
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);
help mean
doc mean
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

Kevin am 3 Jul. 2013
Bearbeitet: Kevin am 3 Jul. 2013
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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by