How to extract the diagonal of a given matrix?
Show older comments
How can I extract the diagonal of a given matrix with using size? I know we can do it directly with diag.
5 Comments
We may?
Thank you.
n = 5;
data = rand(n);
result = nan*ones(1,n);
while sum(isnan(result)) > 0;
checkPosition = randi(n*n,1);
%Am I in the diagonal
[ii,jj] = ind2sub([n,n],checkPosition);
if (ii == jj & rand < 0.00001) %just to make it even more inefficient
result(ii) = data(ii,jj);
end
end
Since this is what looks like a homework question where no effort has been shown, this seems like an adequate answer. You can clean this up to fit your needs and you might learn something in the process.
Edit question originally said "you may use size".
Elruz Rahimli
on 7 Sep 2017
Elruz Rahimli
on 7 Sep 2017
José-Luis
on 7 Sep 2017
Read the documentation on ind2sub() and sub2ind(). Having done that and using the fact that the diagonal of a square matrix is where I == J (keeping the nomenclature from the documentation) would allow you to solve your problem.
Elruz Rahimli
on 7 Sep 2017
Accepted Answer
More Answers (0)
Categories
Find more on Operating on Diagonal Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!