0
votes

I have been trying to get this persistent variable to work and I'm not sure what is wrong. The idea is that I enter a value i.e. 'annualbalance(2000)'. If the value is less than £5000 the interest will be 5% and if its greater than or equal to £5000 then the interest will be 10%. I want to be able to run the function manually as many times as I like until I get a value above, let's say £5100 hence why I have not used a loop.

function annualbalance(x)

persistent annualbalance;
if isempty(annualbalance)
    annualbalance = 0;
elseif annualbalance < 5000
    annualbalance = annualbalance * 1.05
elseif annualbalance >= 5000
     annualbalance = annualbalance * 1.10
end
2
I am struggling to understand your choice of a persistent variable and how you plan to use the function. First year you call annualbalance(2000) which returns 2100. What do you do for the next year? Call annualbalance(2000) again? Call annualbalance(2100)? Not sure what you want. - Daniel
Sorry for not being clear initially, the idea to to replace x with the new value. first: annualbalance(2000) second: annualbalnce(2100) etc - Amber
Then take the answer Cris Luengo provided. There is absolutely no reason to insert persistence. - Daniel

2 Answers

2
votes

I don't think you want to use a persistent variable here. But you do want to output your result. My guess is you want this function:

function x = annualbalance(x)
if x < 5000
   x = x * 1.05
elseif x >= 5000
   x = x * 1.10
end

You can call this function repeatedly like so:

moneys = 1000;   % your start value
moneys = annualbalance(moneys);
moneys = annualbalance(moneys);
moneys = annualbalance(moneys);
moneys = annualbalance(moneys);
moneys = annualbalance(moneys);
moneys = annualbalance(moneys);
moneys           % display the amount you have now after 6 years

If you want to see how many years you need to wait to get a certain amount, you can use a loop as follows:

moneys = 1000;   % your start value
years = 0;       % keeps track of time
while moneys < 5100  % target amount
   moneys = annualbalance(moneys);
   years = years + 1;
end
fprintf('I have %f money after %f years\n', moneys, years);
1
votes

Perhaps you could try to define an output variable and delare the variable (not the function) as persistent:

function annualbalance(x)

persistent out;
if isempty(out)
    out = 0;
elseif out < 5000
    out = out * 1.05
elseif out >= 5000
     out = out * 1.10
end

That is not a good way to code it, however. The variable out will not be accessible outside the annualbalance function. Perhaps it would be better to work with an output variable. Also, your function receives x as an input argument, but x appears nowhere in the function. You should also check that out.