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

답변 (1개)

KSSV
KSSV 2021년 3월 22일
편집: Walter Roberson 2021년 3월 22일

0 개 추천

n = 4 ;
iwant = diag(1:n)
iwant = 4×4
1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4
with loop:
n = 4 ;
iwant = zeros(n) ;
for i = 1:n
iwant(i,i) = i ;
end
iwant
iwant = 4×4
1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4

댓글 수: 9

ukulele
ukulele 2021년 3월 22일
This is not woking did you try it?
Walter Roberson
Walter Roberson 2021년 3월 22일
KSSV did try it. The output you see above for iwant is the output of a MATLAB run.
ukulele
ukulele 2021년 3월 22일
n=input('Bir sayi giriniz=');
k=diag(1:n);
for i=1:n
k(n,n)=n;
end
It happened when I type it like this but k command did not appear in the window
ukulele
ukulele 2021년 3월 22일
n=input('Bir sayi giriniz=');
k=diag(1:n);
for i=1:n
k(n,n)=n;
end
please can you try it again? i can't see k on command window
Walter Roberson
Walter Roberson 2021년 3월 22일
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
KSSV 2021년 3월 22일
You have not taken the output of k. Try printing/ viewing k.
ukulele
ukulele 2021년 3월 22일
because i have to see k on command window :(
Walter Roberson
Walter Roberson 2021년 3월 22일
편집: Walter Roberson 2021년 3월 22일
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
ukulele 2021년 3월 22일
i get it thank youuu

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

질문:

2021년 3월 22일

편집:

Jan
2021년 3월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by