0

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?

Krrr
  • 452
  • 1
  • 3
  • 15

1 Answers1

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.
Daniel
  • 36,610
  • 3
  • 36
  • 69