Issues executing while loop

1 回表示 (過去 30 日間)
Bryan
Bryan 2019 年 7 月 17 日
コメント済み: Star Strider 2019 年 7 月 18 日
Hi guys,
I am not able to run this code. I plan to run this code which will make the 4 values in my DPnew array to be close enough with a certain tolerance percentage. I am using a while loop which works like a do while statement. It is not working all the time though. Sometimes it works and sometimes MATLAB starts to pause and debug the code. What is the issue with it? It is part of an algorithm so changing the formulas for the calculation is not an option.
DPbest = 0.4;
B = rand;
DPold = [0.2;0.4;0.6;0.8];
DPnew = [0;0;0;0];
vold = [0;0;0;0];
vnew = [0;0;0;0];
dataType = 'double';
while true
for i = 1:1:4
f = 0.3 + (0.5-0.3)*B;
vnew(i) = vold(i)+(DPold(i) - DPbest)*f;
if DPold(i) > DPbest
DPnew(i) = DPold(i) - abs(vnew(i));
else
DPnew(i) = DPold(i) + abs(vnew(i));
end
end
vold = vnew;
if abs((max(DPnew)-min(DPnew))/max(DPnew)) < 0.1
break;
end
end

採用された回答

Star Strider
Star Strider 2019 年 7 月 17 日
When I ran the code you posted, the while loop becomes infinite if ‘min(DPnew)’ is negative. In that event, this expression:
abs((max(DPnew)-min(DPnew))/max(DPnew))
appears to increase until it reaches a value of about 3. (I don’t know if it increases beyond that, since I interrupted it before then.)
Trapping negative values of ‘DPnew’ and correcting them, or setting an additional limit on the while condition (for example, adding a counter and setting the additional while condition that the counter does not exceed some value), should solve that problem, or at least prevent the loop from becoming infinite.
I doubt MATLAB is pausing to debug the code.
  7 件のコメント
Bryan
Bryan 2019 年 7 月 18 日
Hi Stryder,
I see what you did there. It is good. Thanks for your help!
Star Strider
Star Strider 2019 年 7 月 18 日
As always, my pleasure!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNaNs についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by