Effacer les filtres
Effacer les filtres

Problem with a for loop

1 vue (au cours des 30 derniers jours)
JD
JD le 3 Juil 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

Réponses (2)

Jonathan Sullivan
Jonathan Sullivan le 3 Juil 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);
For more information, look at the documentation
help mean
doc mean

Kevin
Kevin le 3 Juil 2013
Modifié(e) : Kevin le 3 Juil 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...

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by