normal distribution recalcultation with a while loop

4 visualizaciones (últimos 30 días)
Luis Paniagua
Luis Paniagua el 10 de Dic. de 2019
Respondida: Manikanta Aditya el 20 de Jun. de 2022
Hi there,
I am hav the following code
for i=1:lambda
pop(i).Step=mvnrnd(zeros(VarSize),C{g});
pop(i).Position=M(g).Position+sigma{g}*pop(i).Step.';
pop(i).Cost=CostFunction(pop(i).Position);
i=i+1;
end
I want thar if pop(i).Cost==0, the it restarts the calculations all over againg until I get a value different from 0, I am used to working with C++, where I would use a do while loop, but in matlab I am not sure how to do it,
I tried with a while loop after the previous piece of code, like this:
for i=1:lambda
pop(i).Step=mvnrnd(zeros(VarSize),C{g});
pop(i).Position=M(g).Position+sigma{g}*pop(i).Step.';
pop(i).Cost=CostFunction(pop(i).Position);
while pop(i).Cost ==0
pop(i).Step=mvnrnd(zeros(VarSize),C{g});
pop(i).Position=M(g).Position+sigma{g}*pop(i).Step.';
pop(i).Cost=CostFunction(pop(i).Position);
end
i=i+1
end
But it didnt work, any idea?
  1 comentario
Rik
Rik el 10 de Dic. de 2019
The for loop will increment your iterator for you, the while loop will not. The i=i+1; is not needed in the for loop (as mlint warns you). It is not clear to me what you're attempting to do, but if I understand your description, the code you've posted should do what you mean.

Iniciar sesión para comentar.

Respuestas (1)

Manikanta Aditya
Manikanta Aditya el 20 de Jun. de 2022
Hi,
The given snippet can be done without using while loop as well by simply using an if statement which when triggered reduces i by 1. This makes the loop to run again.
If you have to use while loop only, it can be done by initializing value of pop(i).Cost to 0, before the while loop and carrying out the problem inside the while loop.
Without while loop:
.
for i=1:lambda
pop(i).Step=mvnrnd(zeros(VarSize),C{g});
pop(i).Position=M(g).Position+sigma{g}*pop(i).Step.';
pop(i).Cost=CostFunction(pop(i).Position);
if pop(i).Cost == 0
i = i - 1;
end
end
With while loop:
.
for i=1:lambda
pop(i).Cost = 0;
while pop(i).Cost == 0
pop(i).Step=mvnrnd(zeros(VarSize),C{g});
pop(i).Position=M(g).Position+sigma{g}*pop(i).Step.';
pop(i).Cost=CostFunction(pop(i).Position);
end
end

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by