How to create a 10-by-10 matrix that is all zeros except for ones in the diagonal (runnig from top left to bottom right) using a for-loop?
16 views (last 30 days)
Show older comments
Hello everyone, would someone be so kind as to help me solve this problem? I searched the diagonal documentation and read a suggestion about it in the forum (where they suggested the randperm function), but unfortunately I couldn’t solve it.
Would you be so kind as to suggest a very simple method since I am in the beginning and I know only a few functions. Thank you very much!
2 Comments
David Jacob
on 9 Mar 2021
Hey,
You don't necessarily need a for loop in order to do this. There is a MATLAB function for defining identity matrices:
I = eye(10);
This will do the job. If you prefer using a for loop instead pre-define a 10-by-10 matrix with zeros(10) and fill the diagonal elements with a 1.
I = zeros(10);
for k=1:10
I(k,k) = 1;
end
Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements 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!