Square Matris (diagonal)
Show older comments
With the Nested For loop, the diagonals line number according to the value entered by the user.
I want to write a code that creates a square matrix as many as the number that the user enters, and the other elements that show are zero.Like this if users input 4, i want to see this
1 0 0 0
0 2 0 0
0 0 3 0
0 0 0 4
Answers (1)
KSSV
on 22 Mar 2021
Edited: Walter Roberson
on 22 Mar 2021
n = 4 ;
iwant = diag(1:n)
with loop:
n = 4 ;
iwant = zeros(n) ;
for i = 1:n
iwant(i,i) = i ;
end
iwant
9 Comments
ukulele
on 22 Mar 2021
Walter Roberson
on 22 Mar 2021
KSSV did try it. The output you see above for iwant is the output of a MATLAB run.
ukulele
on 22 Mar 2021
ukulele
on 22 Mar 2021
Walter Roberson
on 22 Mar 2021
Why would you see k in the command window? You have semi-colons after each of your assignment statements, and that means that you do not want any output from the statement. The only output you ask for in the code is the prompt for the input() statement.
KSSV
on 22 Mar 2021
You have not taken the output of k. Try printing/ viewing k.
ukulele
on 22 Mar 2021
Walter Roberson
on 22 Mar 2021
Edited: Walter Roberson
on 22 Mar 2021
n=input('Bir sayi giriniz=');
k=diag(1:n) %notice semi-colon removed
for i=1:n
k(n,n)=n %notice semi-colon removed
end
A statement that ends with a semi-colon does not display its value.
A statement that does not end with a semi-colon always displays its value if it was an assignment statement; if it was not an assignement statement, then in some cases it will show the value and in other cases it will not show the value, depending exactly what you were asking for.
ukulele
on 22 Mar 2021
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!