Summing a 4D matrix without for loops in matlab

2019-07-19 18:58发布

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...

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-19 19:36

what's wrong with

[m n p q] = size( A );
squeeze( sum( reshape( A, [], p, q ), 1 ) )

Alternatively,

squeeze( sum( sum( A, 2 ), 1 ) )
查看更多
别忘想泡老子
3楼-- · 2019-07-19 19:55

Probably fastest:

permute(sum(sum(A)), [3 4 1 2]);

EDIT: nope, Shai's first solution is faster :)

查看更多
登录 后发表回答