MATLAB: Pre-specify user input to function

functionuser input

This is the first time I've posted here, so apologies if it's in the wrong place.
I have a function which takes a user input and I would like to be able to pre-specify the input before the function is called. A basic example is below
function c = myfunc(a,b)
d = input('Enter value for d: ');
c = a + b + d;
end
My function is called inside a loop and I would like to not have to manually enter my 'd' value each time. I also cannot add d to the list of function arguments, because the function is called in lots of other places in the code and I don't want to go through and change them all.
Essentially, I would like the functionality that this bash script (script.sh) has
#!/bin/bash
echo "Specify d: "
read d
echo $d
when called as
./script.sh <<< 5
Is this possible?
Thanks.

Best Answer

You could use a persistent variable:
function c = myfunc(a,b)
persistent d
if isempty(d)
d = input('Enter value for d: ');
end
c = a + b + d;
end
and calling:
>> myfunc(1,2)
Enter value for d: 7
ans =
10
>> myfunc(1,3)
ans =
11
>> myfunc(1,4)
ans =
12
To reset the d value could either add some code (e.g. set d=[] when the function is called with no inputs) or use clear:
>> clear myfunc
>> myfunc(1,5)
Enter value for d: 3
ans =
9
>> myfunc(1,6)
ans =
10