Pre-specify user input to function

10 次查看(过去 30 天)
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.

采纳的回答

Stephen23
Stephen23 2016-8-5
编辑:Stephen23 2016-8-5
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

更多回答(2 个)

Guillaume
Guillaume 2016-8-5
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

Steven Lord
Steven Lord 2016-8-5
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.

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by