Search code examples
performancematlabmultidimensional-arraydiagonal

matlab efficient way to extract diagonals of a 3D matrix


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?


Solution

  • 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.