How can I index the diagonals of a 3-D matrix in MATLAB?

你。 提交于 2019-12-13 00:55:38

问题


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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/5598900/how-can-i-index-the-diagonals-of-a-3-d-matrix-in-matlab

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