How to solve the vertcat problem when using a loop function?

4 ビュー (過去 30 日間)
Cassie Guo
Cassie Guo 2016 年 3 月 27 日
回答済み: Walter Roberson 2016 年 3 月 27 日
I have a problem needs to compute amount of money in a savings account given an initial balance and an annual interest rate of 2.5%.for a number of years starting from next year (2017) and ending at an end year given by the user. And store the answer in two column vector with "Year Balance"
clear
clc
%read and verify user input (skipped for this example)
balance = input('Please enter the initial balance:') ;
useryear = input('Please enter the year:');
%Check user input
while balance <= 0,
disp('Error, the balance should be greater than zero')
end
while useryear < 2017,
disp('Error, the end year should be greater than 2017')
end
numberOfYears = useryear - 2017 + 1;
% initialize interest rate
interestRate = 0.025;
% formula
% new balance = old balance + old balance * interest rate
for k = 1:numberOfYears
newBalance = balance + balance * interestRate;
allbalance(k) = newBalance;
end
fprintf('Year\t Balance\n')
fprintf('%d\t %.2f\n',[2017:useryear;allbalance(k)]);
After running this code, it shows
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
Error in Exercise2 (line 38)
fprintf('%d\t %.2f\n',[2017:useryear;allbalance(k)]);".
Can anyone tell me how to solve this problem? Thanks!

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 3 月 27 日
fprintf('%d\t %.2f\n',[2017:useryear;allbalance].' );

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by