normal distribution recalcultation with a while loop
19 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Rik
am 10 Dez. 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.
Antworten (1)
Manikanta Aditya
am 20 Jun. 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!