Using while loops in matrices
조회 수: 3 (최근 30일)
이전 댓글 표시
I am trying to use while loop to change the diagonal entries of a square matrix rand(10) to 1, and other entries to zero
This code below is changing the whole entries to 1, i am stucked.
m= 1:10
n= 1:10
A = rand(10)
B = size (A)
while m==n
A(m,n) = 1;
if not (m==n)
A(m,n) = 0;
end
break
end
A
답변 (1개)
Pin-Hao Cheng
2022년 12월 17일
Let me know if this is what you are looking for. Happy to answer any further questions!
A = rand(10)
for m = 1:10 % loop through rows
for n = 1:10 % loop through columns
if m == n % check if it's diagonal el
A(m,n) = 1;
else
A(m,n) = 0;
end
end
end
A
댓글 수: 7
Jan
2022년 12월 17일
The pattern:
if m == n
A(m,n) = 1;
else
A(m,n) = 0;
end
can be abbreviated in general to:
A(m, n) = (m == n);
참고 항목
카테고리
Help Center 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!