External function problem.
2 views (last 30 days)
Show older comments
Chett Manly
on 18 Sep 2021
Commented: Chett Manly
on 21 Sep 2021
I am trying to alter this code which I have included and is functioning to use an external function.
After a few attempts but always returning errors I am at an end.
I have tried replacing line 8 and 9 with a function look up and recreating the function in the external file but it throws errors.
I believe it is a simple fix but am a bit stuck.
clear; close all; clc
balance(1) = 1000;
contribution = 1200;
M = 1; % month ticker
interest = 0.0025;
while true %this makes the program run until the break condition is met
M = M + 1; % you need to increment months + 1 every cycle
balance(M) = balance(M-1) + interest*balance(M-1) + contribution;
if balance(end) > 500000;
break;
end
end
years = M/12; %year counter
fprintf('%g Months until $500000 reached\n', M);
fprintf('%g Years until $500000 reached\n', years);
format bank
plot(balance);
grid on
ytickformat('usd')
title('Saving 3% compound')
xlabel('Months')
ylabel('Saving balance')
Label = max(balance) %this labels the plot with max balance
txt = {'Max Balance:',Label,'\leftarrow'};
text(M,Label,txt,'HorizontalAlignment','right')
4 Comments
Image Analyst
on 18 Sep 2021
Please attach the m-file balance.m -- which I guess is your external function.
Accepted Answer
Walter Roberson
on 18 Sep 2021
in MATLAB, assigning to one of the input parameters only causes local changes, not change to variable passed in. To change the variable you need to return the new value and assign it to the appropriate location in the calling function.
3 Comments
Walter Roberson
on 19 Sep 2021
clear; close all; clc
balance(1) = 1000;
contribution = 1200;
M = 1; % month ticker
interest = 0.0025;
while true %this makes the program run until the break condition is met
M = M + 1; % you need to increment months + 1 every cycle
balance = account(balance, contribution, interest, M)
if balance(end) > 500000;
break;
end
end
years = M/12; %year counter
fprintf('%g Months until $500000 reached\n', M);
fprintf('%g Years until $500000 reached\n', years);
format bank
plot(balance);
grid on
ytickformat('usd')
title('Saving 3% compound')
xlabel('Months')
ylabel('Saving balance')
Label = max(balance) %this labels the plot with max balance
txt = {'Max Balance:',Label,'\leftarrow'};
text(M,Label,txt,'HorizontalAlignment','right')
function balance = account(balance, contribution, interest, M);
balance(M) = balance(M-1) + interest*balance(M-1) + contribution;
More Answers (0)
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!