Info

Questa domanda è chiusa. Riaprila per modificarla o per rispondere.

Plotting loop value according to years

1 visualizzazione (ultimi 30 giorni)
torre
torre il 25 Set 2019
Chiuso: MATLAB Answer Bot il 20 Ago 2021
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

Risposte (1)

David K.
David K. il 25 Set 2019
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