Pre-specify user input to function
10 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Stephen23
on 5 Aug 2016
Edited: Stephen23
on 5 Aug 2016
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
More Answers (2)
Guillaume
on 5 Aug 2016
Yes, this is absolutely the right place.
No, it is not possible to programmatically feed an input to the input function.
I don't get the "the function is called in lots of other places in the code and I don't want to go through and change them all.". Using your hypothetical syntax, you would still have to modify each call to prefeed the value.
If you only want to manually input a value once, and reuse the same value thereafter, you can modify the function to use a persistent variable:
function c = myfunc(a,b)
persistent d;
if isempty(d) %only prompt on first call
d = input('Enter value for d: ');
end
c = a + b + d;
end
Note: to reinitialise the persistent variable to empty:
clear myfunc
0 Comments
Steven Lord
on 5 Aug 2016
I would use nargin or separate the computational piece from the interface piece.
nargin based approach
function c = myfunc(a, b, d)
if nargin < 3
d = input('Enter value for d: ');
end
c = a + b + d;
end
separation of concerns approach
function c = myfunc(a,b)
d = input('Enter value for d: ');
c = myfuncImpl(a, b, d);
end
Those places in your code where you need to prompt the user for a value of d would call myfunc.
function c = myfuncImpl(a, b, d)
c = a + b + d;
end
Those places for which d is already known and the code does not need to prompt the user would call myfuncImpl instead of myfunc.
0 Comments
See Also
Categories
Find more on Argument Definitions 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!