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

4 Ansichten (letzte 30 Tage)
Cassie Guo
Cassie Guo am 27 Mär. 2016
Beantwortet: Walter Roberson am 27 Mär. 2016
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!

Antworten (1)

Walter Roberson
Walter Roberson am 27 Mär. 2016
fprintf('%d\t %.2f\n',[2017:useryear;allbalance].' );

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by