Loops: savings, creating vectors, for-loop, if-else
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
azarang asadi
2022-10-19
编辑:azarang asadi
2022-10-19
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!