필터 지우기
필터 지우기

Loops: savings, creating vectors, for-loop, if-else

조회 수: 2 (최근 30일)
Ville
Ville 2022년 10월 19일
편집: azarang asadi 2022년 10월 19일
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

답변 (1개)

azarang asadi
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

카테고리

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

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by