While and If loop with stopping criteria

조회 수: 4 (최근 30일)
EB
EB 2016년 12월 1일
댓글: EB 2016년 12월 1일
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