How to use for loop to iterate over the elements of the initial matrix and keep just the ones in the diagonal.

1 Ansicht (letzte 30 Tage)
Hey, I have a random 3x3 matrix and i need to create a new vector (size 1x3 or 3x1) storing the diagonal using a for loop (and potentially conditions) to iterate over the elements of the initial matrix and keep just the ones in the diagonal.
So bassically i need to get the main diagonal from matrix using for loop.
%Create a 3x3 array with random number from 1 to 100
R= randi([1,100],3,3)
I would appriciate any hints on how to solve it!
Thanks in advance!

Akzeptierte Antwort

Torsten
Torsten am 6 Mai 2022
Bearbeitet: Torsten am 6 Mai 2022
D =[R(1,1);R(2,2);R(3,3)]
or
D = zeros(3,1);
for i=1:3
D(i) = R(i,i);
end
What's the problem ?

Weitere Antworten (0)

Kategorien

Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by