问题描述
我有一个M-by-M-by-N矩阵,它是N个M-by-M矩阵的串联。我想通过取每个M-by-M子矩阵的对角线并将它们连接在一起,将该矩阵缩减为M-by-N矩阵。我怎样才能以简单的矢量化方式做到这一点?
I have an M-by-M-by-N matrix, which is a concatenation of N M-by-M matrices. I want to reduce this matrix to an M-by-N matrix by taking the diagonals of each M-by-M submatrix and concatenating them together. How can I do this in a simple vectorized way?
推荐答案
你可以通过获取对角线的线性索引并使用它来实现它形成一个新的矩阵
You can do it by getting the linear indices of the diagonals and using it to form a new matrix
[M,~,N]=size(A);%# A is your matrix
indx=cumsum([1:(M+1):M^2; M^2.*ones(N-1,M)]);%#diagonal indices
B=A(indx');%'# transpose to get MxN
在上面,我用过〜
忽略该函数的输出。但是,仅当您使用MATLAB R2009b及更高版本时,此功能才有效。如果您的版本早于此版本,请使用虚拟变量。
In the above, I've used ~
to disregard that output from the function. However, this works only if you're using MATLAB R2009b and above. If your version is older than that, use a dummy variable instead.
这篇关于如何在MATLAB中索引3-D矩阵的对角线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!