问题
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