Convert each 2D matrix in a collection of matrices into a diagonal matrix

2 vues (au cours des 30 derniers jours)
Evripidis Papaevripidis le 2 Avr 2020
I have a collection of 2D matrices stored in a 3D matrix, and I want to keep only the elements on the main diagonal of each one. I managed to do this a shown below, how would this be done more efficiently?
A = rand(N,M,M); % my matrix is not really random, this is just an example.
for i = 1:N
A(i,:,:) = diag(diag(squeeze(A(i,:,:))));
end
1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
KALYAN ACHARJYA le 2 Avr 2020

Connectez-vous pour commenter.

Réponse acceptée

Guillaume le 2 Avr 2020
Modifié(e) : Guillaume le 2 Avr 2020
A = A .* permute(eye(size(A, 2), [3 1 2])) %multiply each matrix by the identity matrix which keeps just the diagonal of each
Note that it's a bit odd to stack your matrices along the first dimension. You'd be better off stacking along the third dimension which would remove the need for the squeeze in your loop, and the need for the permute in the above.
I.e. you'd be better off storing A as:
permute(A, [2 3 1]) %move dim 2 into 1st dimension, dim 3 into 2nd dimension, and dim 1 into 3rd
1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Evripidis Papaevripidis le 2 Avr 2020
Thanks, Just what I was looking for!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Operating on Diagonal Matrices dans Help Center et File Exchange

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by