简体   繁体   English

在Matlab中对3D矩阵的特定维度求和

[英]Summing over specific dimension of a 3D matrix in Matlab

I have a 3D matrix in Matlab of size NxMxD and i need to sum over a specific dimension: 我在Matlab中有一个大小为NxMxD的3D矩阵,我需要对特定尺寸求和:

x = rand(5,3,2);
sum1 = sum(x,1);
sum2 = sum(x,2);
sum3 = sum(x,3);

I would obviously expect in the 3 case that the result would be either a 2D matrix or a 3D matrix with 1 dimension of length 1. This is unfortunately not the case. 我显然希望在3种情况下,结果将是2维矩阵或1维长度为1的3D矩阵。不幸的是,情况并非如此。

sum1 and sum2 are 3D matrix with the dimension over which the sum is done of length 1 but sum3 is a 2D matrix. sum1和sum2是3D矩阵,其维数的长度为1,而sum3是2D矩阵。

I would like to be able to get sum1 and sum2 as 2D matrix in the similar way sum3 is being computed. 我希望能够以类似于计算sum3的方式获取sum1和sum2作为2D矩阵。 Is that possible to do using sum only or the only way is to further use for example the squeeze() function ) 是否可以仅使用sum或唯一的方法是进一步使用,例如squeeze()函数)

As @Tommaso says, the third output is 5x3x1, though when you ask for its size MATLAB cuts of trailing ones. 正如@Tommaso所说,第三个输出是5x3x1,尽管当您要求它的大小时,MATLAB会切掉尾随的。

MATLAB, cannot automatically do this in other places, because this would change the matrix/tensor, remember that MATLAB is “primarily” for matrices. MATLAB无法在其他地方自动执行此操作,因为这会改变矩阵/张量,请记住,MATLAB是“主要”用于矩阵。

A 1xn vector is not the same as an nx1 vector, when performing matrix operations. 执行矩阵运算时,1xn向量与nx1向量不同。

Tl;dr, you will have to use squeeze or reshape Tl; dr,您将必须使用squeezereshape

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM