Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Plotting loop value according to years

1 回表示 (過去 30 日間)
torre
torre 2019 年 9 月 25 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
I have problem plotting loop values. I tried to plot trendline of sum (b) of each round according to years. So that the updatet value is plottet with respect to that year. What I'm doing wrong?
b=5000;
i=0.03;
ii=0.05;
y=0;
years=20;
while y<years
y=y+1;
if b>=8000;
b=b*(1+ii);
else
b=b*(1+i);
end
end
bal=b
plot(y,bal,'b-')
xlabel('Years')
grid on

回答 (1 件)

David K.
David K. 2019 年 9 月 25 日
The problem is that the value b is not being saved within the loop, so your plot function is trying to plot a single value which does not really work. I would change it as such:
b=5000;
i=0.03;
ii=0.05;
y=0;
years=20;
bal = zeros(1,years); % pre allocate b (it's good practice not entirely needed)
bal(y+1) = b; % save the first value of b
while y<years
y=y+1;
if b>=8000;
b=b*(1+ii);
else
b=b*(1+i);
end
bal(y+1) = b; % save the value of b created
end
y = 0:years; % y also needs to be a vector and not a single value
plot(y,bal,'b-')
xlabel('Years')
grid on

Community Treasure Hunt

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

Start Hunting!

Translated by