how i can perform this for loop
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Tammun filistin
el 22 de Jun. de 2018
Editada: Tammun filistin
el 22 de Jun. de 2018
Hello im trying to perform this cod 20 times but the for loop moves one time"j=1 instead of 20" could anyone please help me to solve it!
clear all
close all
clc
for j=1:20
c=[1 2 3 5 6 7 8 99 9 3 4 55 66 7 8 9 9 97 0 1 2 ];
for k=1:length(c)
if c(k)>=5
ag(k)=1
k1=k
return
elseif c(k)<=-1
ag(k)=0
k1=k;
return
else
end
end
m=k1
l(j)=sum(ag)
end
j
2 comentarios
Stephen23
el 22 de Jun. de 2018
"Hello im trying to perform this cod 20 times but the for loop moves one time j=1 instead of 20"
Because that is exactly what you wrote your code to do. On the first loop iteration, where j=1, it reaches the inner loop. The inner loop iterates four times until the first if condition is true (because c(4)==5) upon which you call return. The end.
The return help describes clearly that it returns to the calling function or the command window. And your code clearly run the inner loop until k=4 and so the first condition is true and so you call return, which ends the evaluation of your code. That is what you wrote the code to do, so that is what it does.
Hint: instead of guessing what MATLAB functions and commands do, read their help and try their examples.
Respuesta aceptada
Pieter Hamming
el 22 de Jun. de 2018
Replace "return" by "continue". "Return" stops the whole file, "continue" sends it on to the next iteration in the for loop.
1 comentario
Tammun filistin
el 22 de Jun. de 2018
Editada: Tammun filistin
el 22 de Jun. de 2018
Más respuestas (1)
Meade
el 22 de Jun. de 2018
You're using the return function.
This exits out of the j loop. Try instead replacing return with continue. I'm able to get j to iterate to 20 with that small change.
Best, Meade
clear all
close all
clc
for j=1:20
c=[1 2 3 5 6 7 8 99 9 3 4 55 66 7 8 9 9 97 0 1 2 ];
for k=1:length(c)
if c(k)>=5
ag(k)=1
k1=k
continue
elseif c(k)<=-1
ag(k)=0
k1=k;
continue
else
end
end
m=k1
l(j)=sum(ag)
end
j
%% 20th iter
ag =
0 0 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1
k1 =
18
m =
18
l =
13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13 13
j =
20
1 comentario
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!