Optimization: I cant figure out why my while loop doesn't stop?

조회 수: 1 (최근 30일)
Michael Lynch
Michael Lynch 2020년 5월 25일
편집: Katalin 2020년 5월 25일
I have a for function inside of a for loop which is inside of a while loop. The loop should be stopping before it reaches the 10,000.
%% Declaration
a = 10;
b = 9.5;
r = 0;
i = 1;
s = 92101;
h = 0.5;
n = s + i + r;
yes = 0;
inc = 0;
numberBeds = 267.093;
%% Get numbers
while yes == 0
% Get infected
for k = 1:1:1000
[ sN, iN, rN ] = DiseaseStep( s, i, r, n, a, b, h );
sN(k) = sN;
iN(k) = iN;
rN(k) = rN;
[m,~] = max(iN);
m = m * 0.024;
end
% Stop loop if
if m >= numberBeds
yes = 0;
else
yes = 1;
end
% Increment
inc = inc + 1;
% end loop
if inc == 10000
yes = 1;
else
yes = 0;
end
% Increase beds
numberBeds = numberBeds + 0.001;
% Adjust budget
budget = budget + (0.001 * 5000);
% Decrease a
a = a - 0.001;
end
function [ SOut, IOut, ROut ] = DiseaseStep( s, IIn, RIn, n, a, b, h )
%DiseaseStep This function is going to take in the values needed to
%calculate change over time and then change. Then, it is going to calculate
%the values of I,S,R after one step
n = s + IIn + RIn;
IOut= IIn+(h*(((a.*s.*IIn)./n)-(IIn/b))); %equation
SOut= s+(h*((-a.*s.*IIn)./n));
ROut= RIn+(h*(IIn/b));
end

채택된 답변

Katalin
Katalin 2020년 5월 25일
편집: Katalin 2020년 5월 25일
In this part you set yes == 0 in every loop before inc reaches 10000. So even if your other condition sets it to yes == 1, it will not stop before inc == 10000 because you set yes == 0. A 'while' loop it always finishes one full loop before checking the condition, it does not check it midway.
if inc == 10000
yes = 1;
else
yes = 0;
end
You could use the statement "break" if you want to break continuing the while loop.
if m >= numberBeds
yes = 0;
else
yes = 1;
break
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by