问题
I have a 4D matrix A of size m × n × p × q. Consider B = A(:,:,1,1) which is an m × n matrix. I want to sum all the elements of B to give a number. I want to do this for all such B matrices for all A so finally I will have a p by q matrix.
How can i do this without for loops?
As an example for a 3D matrix (for example A be a 3D matrix) I think this works,
sum(squeeze(sum(A,1)),1)
But I don't know how to do this for a 4D matrix...
回答1:
what's wrong with
[m n p q] = size( A );
squeeze( sum( reshape( A, [], p, q ), 1 ) )
Alternatively,
squeeze( sum( sum( A, 2 ), 1 ) )
回答2:
Probably fastest:
permute(sum(sum(A)), [3 4 1 2]);
EDIT: nope, Shai's first solution is faster :)
来源:https://stackoverflow.com/questions/24508751/summing-a-4d-matrix-without-for-loops-in-matlab