Loops: savings, creating vectors, for-loop, if-else
2 views (last 30 days)
Show older comments
You have 2000$ on a bank account. Annual interest is 7%, and when the savings reach 10000$, the annual interest rise to 9%.
Saving time 30 years.
Variable balanceV must be of size [31 3], but with script below you got [1 1].
How do I collect the data from the loop in one vector size of [31 3]?
balanceV = 2000;
r1 = 0.07; %Interest rate when under 10000
r2 = 0.09; %Interest rate when over 10000
years = 30;
for y = 1:years
balanceV = balanceV * (1+r1);
if balanceV < 10000;
r1 = r1;
else
r1 = r2;
end
end
0 Comments
Answers (1)
azarang asadi
on 19 Oct 2022
Edited: azarang asadi
on 19 Oct 2022
You haven't clearly expressed what you are trying to save in the for loop. [31 3] this means 3 variables saved with 31 iterations in the for loop so I assumes as you only have balanceV and r1 and r2 in the for loop, those are the variables you need to save, so first column corresponds to balanceV, second to r1 and third to r2:
balanceV = 2000;
r1 = 0.07; %Interest rate when under 10000
r2 = 0.09; %Interest rate when over 10000
years = 30;
storage = zeros(31,3); % the first column of this is balanceV, second is r1 and third is r2.
storage(1,1) = balanceV;
storage(1,2) = r1;
storage(1,3) = r2
for y = 2:years % start from 2 as the first row is already filled for the initialized values.
balanceV = balanceV * (1+r1);
if balanceV < 10000;
r1 = r1;
else
r1 = r2;
end
storage(y,1) = balanceV;
storage(y,2) = r1;
storage(y,3) = r2;
end
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!