How to extract the diagonal of a given matrix?

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".
Sorry, I just copied it from the source.I should have rephrased it. Doing it right now.
I know I already crossed the line but I cannot get any response from MATLAB when I type the code. I think there should be a simpler solution (probably involving size).
You can ignore me if you are inclined to do so.
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.
Thank you for the directions. I am doing it.
Too bad that I cannot upvote in the comments section.

Sign in to comment.

 Accepted Answer

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!