Clear Filters
Clear Filters

Using while loops in matrices

4 views (last 30 days)
Olabayo
Olabayo on 17 Dec 2022
Commented: Walter Roberson on 17 Dec 2022
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

Answers (1)

Pin-Hao Cheng
Pin-Hao Cheng on 17 Dec 2022
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 Comments
Jan
Jan on 17 Dec 2022
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 on 17 Dec 2022
The whole thing abbreviates to a call to eye() and size()

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!