Borrar filtros
Borrar filtros

Info

La pregunta está cerrada. Vuélvala a abrir para editarla o responderla.

Problem executing While loop

1 visualización (últimos 30 días)
NIMA RAHMANI MEHDIABADI
NIMA RAHMANI MEHDIABADI el 2 de Abr. de 2019
Cerrada: MATLAB Answer Bot el 20 de Ag. de 2021
So I'm trying to change my code from a for loop to while loop to display numbers from 10 to 30 and skips numbers from 15 to 20 and also 28. I did the for loop but however when i try to write it using a while loop i get an error.
This is for my for loop:
clear;
disp('This is the for loop version')
for k = 10:30
if (k > 15 && k < 20) || (k == 28)
continue
end
disp(k)
end
here is my while loop:
clear;
disp('This is the for while version')
k = 10;
while( k <= 30 )
if (k > 15 && k < 20) || (k == 28)
disp(k);
k = k + 1;
end
end
Also how do i stop the while loop from running? when i hit the run button it never stop running.
Thanks
  1 comentario
Guillaume
Guillaume el 2 de Abr. de 2019
Editada: Guillaume el 2 de Abr. de 2019
Your question about the while loop has been answered. Note that the for loop version could be much simpler. Nothing is forcing you to pass a vector of continuous values to for, so:
for k = [10:15, 20:27, 29:30]
disp(k)
end
%that's it!

Respuestas (1)

Jim Riggs
Jim Riggs el 2 de Abr. de 2019
Editada: Jim Riggs el 2 de Abr. de 2019
You need to move the statement
k=k+1
outside of the if block.
The first time you run the while loop, k has a value of 10, and the "if" test fails. K never gets updated.
k=10
while k<=30
if(k>15 && k<20) || k=28
dsp(k)
end
k=k+1
end
  1 comentario
madhan ravi
madhan ravi el 2 de Abr. de 2019
+1, disp(k)

La pregunta está cerrada.

Etiquetas

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by