What is the matter with this nested looped?

The below is my code, but it can product the same result as the above.
n = input('Enter a number: ');
A = zeros(n);
for x = n:1
for y = 1:n
A(n-(n-x),n-(n-y)) = 1;
end
end

3 comentarios

Atsushi Ueno
Atsushi Ueno el 5 de Jun. de 2021
Editada: Atsushi Ueno el 5 de Jun. de 2021
for x = n:1
if n is natural number, this iterator x makes no action because n > 1.
if you would like to make such a iterator x, you should write,
for x = n:-1:1
A(n-(n-x),n-(n-y)) = 1;
n-(n-x) is same as x, and n-(n-y) is same as y. What is your intention?
To debug your code, how about removing semi-colon to display the result of A for each iteration?
A(n-(n-x),n-(n-y)) = 1

Iniciar sesión para comentar.

Respuestas (1)

Scott MacKenzie
Scott MacKenzie el 5 de Jun. de 2021
Most likely the problem is with this line
for x=n:1
if n > 1, the loop does not execute. Did you mean
for x=1:n

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Productos

Versión

R2019a

Preguntada:

el 5 de Jun. de 2021

Respondida:

el 5 de Jun. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by