Reputation: 295
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...
Upvotes: 2
Views: 514
Reputation: 38032
Probably fastest:
permute(sum(sum(A)), [3 4 1 2]);
EDIT: nope, Shai's first solution is faster :)
Upvotes: 2
Reputation: 114816
what's wrong with
[m n p q] = size( A );
squeeze( sum( reshape( A, [], p, q ), 1 ) )
Alternatively,
squeeze( sum( sum( A, 2 ), 1 ) )
Upvotes: 3