Using while loops in matrices
Mostrar comentarios más antiguos
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 comentario
Torsten
el 17 de Dic. de 2022
A = rand(10);
A = eye(10);
Respuestas (1)
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 comentarios
Olabayo
el 17 de Dic. de 2022
How about this:
% Initialize matrix A with random values
N = 5;
A = rand(N)
% processing the elements
while N > 0
A(N,:) = 0;
A(N,N) = 1;
N = N-1;
end
A
A = rand(10)
m = 1;
while m <= 10 % loop through rows
n = 1;
while n <= 10 % loop through columns
if m == n % check if it's diagonal el
A(m,n) = 1;
else
A(m,n) = 0;
end
n = n + 1;
end
m = m + 1;
end
A
Pin-Hao Cheng
el 17 de Dic. de 2022
Olabayo
el 17 de Dic. de 2022
Jan
el 17 de Dic. de 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
el 17 de Dic. de 2022
The whole thing abbreviates to a call to eye() and size()
Categorías
Más información sobre Creating and Concatenating Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!