How would I make a script to find the Diagonal of a matrix?

1 view (last 30 days)
I know you could simply use the Diag function but I am playing around with making scripts and I am curious.

Answers (2)

Star Strider
Star Strider on 11 Feb 2018
Edited: Star Strider on 11 Feb 2018
Hi, Curious Alicia Gillies!
I would do this:
M = ...; % Your Matrix
for k = 1:min(size(M))
diagM(k) = M(k,k);
end
and to create a diagonal matrix from the same ‘diagM’ (or any other) vector:
N = eye(numel(diagM)) .* diagM(:);

Walter Roberson
Walter Roberson on 11 Feb 2018
diagM = @(M) M(1:size(M,1)+1:size(M,1)*min(size(M))).';

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!