Summing a 4D matrix without for loops in matlab

断了今生、忘了曾经 提交于 2020-01-05 03:02:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!