Is it possible to write a MATLAB script that can give command line input to a function? - matlab

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:
function a=input(str)
% THIS IS THE DUMMY VERSION OF THE
% MATLAB BUILT-IN FUNCTION "input"
global dummy_input
disp('WARNING!!!')
disp('MATLAB "input" built-in function overridded')
disp(['Setting dummy_inpt'])
a=dummy_input;
end
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:
global dummy_input
x=3;
dummy_input=123;
y=my_func(x)
dummy_input=42.13;
y=my_func(x)
If my_func is the function you post in the question, you will obtain:
WARNING!!!
MATLAB "input" built-in function overridded
Setting dummy_inpt
y =
126
WARNING!!!
MATLAB "input" built-in function overridded
Setting dummy_inpt
y =
45.1300
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:
global input_list
input_list=[27 30 5 31 21]
In the "dummy" input function, the first element of the array is assigned to the output variable, then the it is deleted:
a=input_list(1);
input_list(1)=[];
the code of the updated version of the function is the following:
function a=input(str)
% THIS IS THE DUMMY VERSION OF THE
% MATLAB BUILT-IN FUNCTION "input"
global input_list
disp('WARNING!!!')
disp('MATLAB "input" built-in function overridded')
disp(' ')
disp(' ')
disp(' ')
if(isempty(input_list))
error('Error in DUMMY input: no more input data')
else
disp(['Setting dummy_input ' num2str(input_list(1))])
a=input_list(1);
disp(' ')
disp(' ')
disp(' ')
input_list(1)=[];
end
end
An error is generated in case the input array becomes empty (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.

Related

Matlab: Call function that has no outputs from an anonymous function

I'd like to call a certain function from within an anonymous function, as in
#(){fooBar(baz)}
Trouble is, fooBar has no outputs, which makes the anonymous function complain. Is there a way around this besides making the fooBar function return a dummy output?
The problem is in your anonymous function definition. By enclosing your function foobar(baz) between the characters {...}, you are programming a function which has to :
evaluate the expression foobar(baz)
Place the result of this expression into a cell
return the cell
Obviously in step (2) Matlab cannot place the result of the expression (1) in a cell because there is no output from (1).
So simply define your function without the curly braces:
myFunction = #() fooBar(baz)
and everything should work ok.
To demonstrate with an example, let's define the function fooBar by doing something which does not produce an output (change an axe limits for example):
fooBar = #(axlim) set(gca,'XLim',axlim)
I can now call fooBar([0 20]) and the current axes will directly have its axes limits set to [0 20]
If there is an axis span which I use often ([-5 5] for example), I could be tempted to define a new function which will always call fooBar with the same (often used) parameters:
fooBarPrefered = #() fooBar([-5 5])
Now every time I call fooBarPrefered(), my axes X limits are directly set to [-5 5].
To further prove the point, since calling fooBar([-5 5]) does not produce an output, Matlab will indeed complain if I define my function with curly braces:
fooBarPrefered = #() {fooBar([-5 5])} ;
>> fooBarPrefered()
One or more output arguments not assigned during call to "set".
Error in #(axlim)set(gca,'XLim',axlim)
Error in #(){fooBar([-5,5])}
But note that this is the same error than if you were trying to assign the output of fooBar to a variable directly in the workspace:
a = fooBar([0 20])
One or more output arguments not assigned during call to "set".
Error in #(axlim)set(gca,'XLim',axlim)
Bottom line: If a function does not have an output, do not try to redirect this output to a variable or an expression.

Correct use of tilde operator for input arguments

Function:
My MATLAB function has one output and several input arguments, most of which are optional, i.e.:
output=MyFunction(arg1,arg2,opt1,opt2,...,optN)
What I want to do:
I'd like to give only arg1, arg2 and the last optional input argument optN to the function. I used the tilde operator as follows:
output=MyFunction(str1,str2,~,~,...,true)
Undesired result:
That gives the following error message:
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
The error points to the comma after the first tilde, but I don't know what to make of it to be honest.
Problem identification:
I use MATLAB 2013b, which supports the tilde operator.
According to MATLAB's documentation the above function call should work:
You can ignore any number of function inputs, in any position in the argument list. Separate consecutive tildes with a comma...
I guess there are a few workarounds, such as using '' or [] as inputs, but I'd really like to understand how to correctly use '~' because actually leaving inputs out allows me to use exist() when checking the input arguments of a function.
If you need any further info from me, please let me know.
Thank you very much!
The tilde is only for function declaration. Matlab's mlint recommends to replace unused arguments by ~. The result is a function declared like this function output = MyFunction(a, b, ~, c). This is a very bad practice.
Since you have a function where the parameters are optional, you must call the function with empty arguments output=MyFunction(str1,str2,[],[],...,true).
A better way to do it is to declare the function with the varargin argument and prepare your function for the different inputs:
function output = MyFunction(varargin)
if nargin == 1
% Do something for 1 input
elseif nargin == 2
% Do something for 3 inputs
elseif nargin == 3
% Do something for 3 inputs
else
error('incorrect number of input arguments')
end
It is even possible to declare your function as follows:
function output = MyFunction(arg1, arg2, varargin)
The declaration above will tell Matlab that you are expecting at least two parameters.
See the documentation of nargin here.
... and the documentation of varargin here
To have variable number of inputs, use varargin. Use it together with nargin.
Example:
function varlist2(X,Y,varargin)
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d):\n',nVarargs)
for k = 1:nVarargs
fprintf(' %d\n', varargin{k})
end

If Statement Matlab Function on Simulink

I am trying to made my own Matlab function to use in Simulink but I have not success. It is a simple If statement with one input and three output values,all of them integer, here the code:
function [ PWM,INA,INB ] = VNH5019(in_Motor)
if in_Motor ==0
INA=0;
INB=0;
PWM=0;
elseif in_Motor>0
if in_Motor>255
in_motor=255;
end
INA=1;
INB=0;
PWM=in_Motor;
elseif in_Motor<0
if in_Motor<-255
in_motor=-255;
end
INA=0;
INB=1;
PWM=-in_Motor;
end
And here the error:
Output argument 'PWM' is not assigned on some execution paths.
Function 'MATLAB Function' (#38.28.35), line 1, column 29:
"VNH5019"
You should probably replace that line:
elseif in_Motor<0
with a simple else.
Try to assing a value to the variables before the ifs. Simulink needs values to be always defined in this type of block functions and it seems that in yours they are, but the compiler thinks they are not. So before any if, asign some value to your outputs.
It will probably work.

Anonymous function inside a script error

I created an anonymous function inside a script and I can't get MATLAB to run the fminsearch? Here's an what I have so far:
V=x(1);
f=x(2);
q=#(x) (pi.*D.*L)./(1000.*V.*f);
fminsearch(#q,x);
The variables D and L are defined, but MATLAB gives me the following error:
Error: File: Testing.m Line: 51 Column: 17
"q" was previously used as a variable, conflicting with its use here as the name of a function or command.
See "How MATLAB Recognizes Command Syntax" in the MATLAB documentation for details.
q is not mentioned before this command. What am I doing wrong?
Another thing that could solve my problem is to get my script to write a function file, but how to do that?
Remove the second #:
V=x(1);
f=x(2);
q=#(x) (pi.*D.*L)./(1000.*V.*f);
fminsearch(q,x);
q is a function handle. fminsearch expects a function handle. You can create a function handle out of a function using an # (e.g. #min), but you don't need to do that here.
You can also write the anonymous function inline with the search command:
V=x(1);
f=x(2);
fminsearch(#(x) (pi.*D.*L)./(1000.*V.*f),x);
UPDATE (credits to #wakjah)
For your code to do anything sensible, you should use the argument x of the anonymous function:
x0 = [initialV, initialF];
fminsearch(#(x) (pi.*D.*L)./(1000.*x(1).*x(2)), x0);
#function creates a function handle for an existing function.
q = #(x) whatever... creates a function handle called q.
But, you can't create a function handle for a function handle, only for a function.
See this:
>> fones = #ones
fones =
#ones
>> ffones = #fones
Error: "fones" was previously used as a
variable,
conflicting with its use here as the name
of a function or command.
See MATLAB Programming, "How MATLAB
Recognizes Function Calls That Use
Command Syntax" for details.
In Matlab, a function handle is a kind of a pointer to a function and is distinct from a function (unlike in some other languages where the a function identifier can be passed and stored as any other variable).
It's important to note that calling a function and a function handle results in the same behaviour. Except for the case where the identifier is used without any parentheses following it:
>> ones
ans =
1
>> fones
fones =
#ones
>> ones(2)
ans =
1 1
1 1
>> fones(2)
ans =
1 1
1 1

How to write a function that does not throw a "wrong number of arguments" error

I am trying to write a minimal function that can be called with a variable number of arguments but that will not throw a wrong number of arguments error if miscalled.
Here is where I start from :
function varargout=fname(varargin)
% FNAME
% Usage: output=fname(input)
% Arguments check
if(nargin~=1 || nargout~=1)
disp('Function fname requires one input argument');
disp('and one output argument');
disp('Try `help fname`');
varargout(1:nargout)={0};
return;
end
input=varargin{1};
output=input;
varargout(1)={output};
end
However this does not work as I would like it to. Is there a way to write a function that :
never throw a "wrong number of arguments" error (so that the rest of the execution can continue)
accepts variable number of input and output arguments and checks them inside the function
(maybe more tricky) if the number of input / output arguments is not correct, does not replace the value of the provided output arguments (so that any misplaced call does not erase the previous value of the output argument)
I am open to any suggestions / other methods.
Thank you for your help.
UPDATE: thanks to #Amro for his answer, I guess what I miss here is either a call by address of reference for Matlab functions or a way to interrupt a function without returning anything and without stopping the rest of the execution.
Here is one way to implement your function:
function varargout = fname(input,varargin)
%# FNAME
%# Usage: output=fname(input)
%%# INPUT
if nargin<1
varargout(1:nargout) = {[]};
warning('Not enough input arguments.'), return
end
if ~isempty(varargin)
warning('Too many input arguments.')
end
%%# YOUR CODE: manipulate input, and compute output
output = input;
%%# OUTPUT
varargout{1} = output;
if nargout>1
warning('Too many output arguments.')
varargout(2:nargout) = {[]};
end
end
Obviously you can customize the warning messages to your liking...
Also, if you want your function to simply print the message instead of issuing warnings, replace all WARNING calls with simple DISP function calls.
Examples of function call:
fname()
fname(1)
fname(1,2)
x = fname()
x = fname(1)
x = fname(1,2)
[x,y] = fname()
[x,y] = fname(1)
[x,y] = fname(1,2)
The above calls execute as expected (showing warning messages when applicable). One caveat though, in the last three calls, if the variable y already existed in the workspace prior to the calls, it would be overwritten by the empty value y=[] in each...
If I understand your question correctly, then the answer is no. If a caller calls a function like this:
[a, b, c] = fname('foo');
then fname is required to return (at least) three outputs. There's no way to tell MATLAB that it should leave b and c alone if fname only returns one output.