While and If loop with stopping criteria

9 次查看(过去 30 天)
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!

采纳的回答

Adam
Adam 2016-12-1
编辑:Adam 2016-12-1
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.
  1 个评论
EB
EB 2016-12-1
Thank you for the reply. I've deleted the second part o with if statements and added cell arrays to store the values of interest like
Error_iter{iter} = Error;
BestSol_iter{iter} = BestSol.Cost;
Now the while loop is working properly.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by