matlab efficient way to extract diagonals of a 3D

2019-09-14 12:43发布

问题:

This question already has an answer here:

  • Extract diagonal element from each frontal slice of tensor 3 answers

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.