How to iterate through 4Th array dimension a summation over the first 3 dimensions
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Dear all,
I am struggling to program this passage of my code:
being S a 4D-double 3x3x4x181 I need to iterate the sum of the matrix(3x3x4) over all the the 181 stored matrices. The following code gives wrong results and I do not understand why.
A = [0.0 0.0 0.0 ; 0.0 0.0 0.0 ; 0.0 0.0 0.0] ;
for i = 1:1:181 ;
for k = 1:1:4
A(:,:,i) = A(i) + S(:,:,k,i)*[ 0.1 0.1 0.1 0.1] ;
end
end
even if I pick a single stored matrix to operate lead to a wrong result...
A = [0.0 0.0 0.0 ; 0.0 0.0 0.0 ; 0.0 0.0 0.0] ;
for i = 1:1:181 ;
for k = 1:1:4
A = A + S(:,:,k,61)*[ 0.1 0.1 0.1 0.1] ;
end
end
I obtain the right results only using a single loop as follow:
A = [0.0 0.0 0.0 ; 0.0 0.0 0.0 ; 0.0 0.0 0.0] ;
for k = 1:1:4
A = A + S(:,:,k,61)*[ 0.1 0.1 0.1 0.1] ;
end
But I really need to iterate this operation along the 4Th dimension of the array, and I do not understand why the first approach does not work.
I hope to find some help here.
Kind regards, Edoardo
0 Commenti
Risposte (1)
Roger Stafford
il 11 Apr 2016
Modificato: Roger Stafford
il 11 Apr 2016
A = sum(reshape(S,3*3*4,181),1);
This will give you a vector with 181 elements, each being the sum over all the first three dimensions for each of the 181 fourth dimension levels.
Added later:
In case I have misinterpreted your request and what you want is the sum along the 4th dimension for each of the 3*3*4 = 36 positions in the first three dimensions, that can be done this way:
A = sum(S,4):
It will give you a 3 x 3 x 4 array of sums.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!