I am writing MATLAB code that will fit together with other MATLAB functions that I cannot modify. Some of these existing functions take input from the command line. Is there a way I can write a test script in MATLAB that can call these functions, and then provide the input as the user would? ie. if I have a function:
function y = f(x)
z = input('Enter number: ');
y = x + z;
end
Is there a way to have a script call f and provide z?
If you are looking for a non elegant solution.
If you are looking for a potentially dangerous solution.
Then you might try this: write a function named "input" as follows:
Declare a
global
variable either in the script you use to test the function and in your "dummy"input
function.Assign the desired value to the
global variable
as follows:If
my_func
is the function you post in the question, you will obtain:I've added the printing of the warnings in the "dummy" input function yust as a remainder ...
You do not need to modify the function you want to test, when it will call
input
to get a number from the user, it will call your "dummy" input.Version 2 of the "dummy" input function
This version of the "dummy" input function allows autonatically handling multiple request of input values.
It requires the user knows in advance how many times the "original"
input
function is called.No additional
global counter
is required.It is sufficient the change the definition of the
global parameter
in the script, declaring it as an array containing the set of input the user want to assign:In the "dummy"
input
function, the first element of the array is assigned to the output variable, then the it is deleted:the code of the updated version of the function is the following:
An
error
is generated in case the input array becomesempty
(by deleting its element at each call) before the end of the script.I've also added some calls to
disp
to make more "clear" the output on the Command Window.Also the "dummy"
input
function print a message on the Command Window telling which input values has been assigned.Make sure to remove your dummy "input" function at the end
Hope this helps.