How can I index the diagonals of a 3-D matrix in MATLAB?
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开发者_StackOverflow 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
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.
精彩评论