matlab efficient way to extract diagonals of a 3D matrix [duplicate]

帅比萌擦擦* 提交于 2019-12-25 06:40:23

问题


I want to extract diagonals of a 3D matrix (Sigma below) into another 3D matrix (Sigma2 below).

Sigma = repmat(magic(4),1,1,3);
Sigma2 = nan(1,4,3);
for i=1:3
    Sigma2(1,:,i) = diag(Sigma(:,:,i));
end

Is there a more efficient way for doing this?


回答1:


You can. If you reshape Sigma to a matrix, selecting the diagonal of the 3D matrix is now selecting rows from a matrix.

Sigma3=reshape(Sigma,[],size(Sigma,3));
Selector=diag(true(size(Sigma,1),1));
Sigma2=Sigma3(Selector(:),:);
%Sigma2=permute(Sigma2,[3,1,2]) %optional last step to get a result with the same dimensions.


来源:https://stackoverflow.com/questions/36060168/matlab-efficient-way-to-extract-diagonals-of-a-3d-matrix

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