While and If loop with stopping criteria
4 views (last 30 days)
Show older comments
I am trying to write a while loop with a stopping criteria, but I have difficulties in implementing this. So, within the loop I have to execute a function to calculate a structure array out. After that I have to find an error by comparing field from structure array out and that is the present value BestSol_Iter with the previous one BestSol.Cost. If the error is greater than 1e-6 then I have to execute the function again and evaluate the error Error = BestSol.Cost - BestSol_Iter. My stopping criteria is Tol= 1e-6.
I have started like this:
iter = 0; %Starting iteration
Tol = 1e-6; %Tolerance criteria for best cost
Error = 1; %Starting initial error
%Call the PSO function to calculate out structure
out = PSO_EBW_SD(problem, params);
BestSol = out.BestSol;
BestCosts = out.BestCosts;
particle = out.pop;
%START THE WHILE LOOP
while (Error > Tol)
BestSol_Iter = BestSol.Cost;
%Run the PSO function to calculate out structure
out = PSO_EBW_SD(problem, params);
%Print the out
BestSol = out.BestSol;
BestCosts = out.BestCosts;
particle = out.pop;
%Calculate the error
Error = BestSol.Cost - BestSol_Iter;
if Error <= Tol
break
if Error > Tol
continue
end
end
end
At the end I want to have the info about numbers of iterations necessary to satisfy the stopping criteria Tol=1e-6. Also I want to save the out structure for every iteration.
Tips and suggestions are very welcome.
Many thanks!
0 Comments
Accepted Answer
Adam
on 1 Dec 2016
Edited: Adam
on 1 Dec 2016
iter = 1;
while( Error > Tol )
...
out{iter} = PSO_EBW_SD(problem, params);
...
iter = iter + 1;
end
Just use a counter like above. Obviously you will need to update your code accordingly to reference out{iter} or assign it to out as you are now, use it as you are now and then put it in a cell array before the end of the loop.
This code is un-necessary though:
if Error <= Tol
break
if Error > Tol
continue
end
end
For a start the 2nd if will never execute because it is in direct opposition to the if statement it sits inside and the first if statement is superfluous because the while condition will pick this up at the start of the next loop anyway.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!