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

3 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by