Using while loops in matrices

조회 수: 3 (최근 30일)
Olabayo
Olabayo 2022년 12월 17일
댓글: Walter Roberson 2022년 12월 17일
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
Torsten
Torsten 2022년 12월 17일
A = rand(10);
A = eye(10);

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

답변 (1개)

Pin-Hao Cheng
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)
A = 10×10
0.1406 0.9234 0.5213 0.0271 0.2317 0.3967 0.3776 0.4847 0.3080 0.0222 0.4363 0.4473 0.2888 0.3199 0.6071 0.3528 0.3311 0.5584 0.4040 0.2190 0.2656 0.6738 0.6987 0.3731 0.8456 0.9905 0.1035 0.4882 0.4701 0.2163 0.0655 0.9590 0.1978 0.6575 0.6074 0.2159 0.2553 0.3445 0.9210 0.6419 0.8856 0.9335 0.8339 0.5396 0.2503 0.0700 0.4051 0.7461 0.3052 0.1634 0.4934 0.4743 0.6264 0.2365 0.6042 0.4961 0.4183 0.7427 0.0465 0.3843 0.2964 0.5497 0.6846 0.4194 0.2852 0.9456 0.7047 0.9608 0.4107 0.6736 0.7785 0.3134 0.1016 0.5672 0.2764 0.7794 0.3809 0.2773 0.2288 0.1847 0.6817 0.5795 0.6303 0.4710 0.6249 0.1779 0.3139 0.5706 0.5860 0.4254 0.6862 0.1720 0.4387 0.9392 0.0916 0.3381 0.4475 0.3649 0.5224 0.7542
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
A = 10×10
1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
  댓글 수: 7
Jan
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);
Walter Roberson
Walter Roberson 2022년 12월 17일
The whole thing abbreviates to a call to eye() and size()

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

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by