Str2Func matlab doesnt run the function - matlab

I am having a problem using str2func, when matlab says that the function i called to is
'undefined function 'X' for input or arguments of type 'double'.
There is a string which is stored in Shape.
Shape gets its string from a function, which gives Shape different values randomly.
I have a function for each shape, so for example if Shape gets the value square, there is also a function named square, and i want to call that function according to the string that is stored in Shape.
so i wrote this:
f=str2func(shape);
f(x0,y0);
function [] = vav(x0,y0)
x=[x0 x0+1 x0+1 x0+2 x0+2 x0];
y=[y0 y0 y0+3 y0+3 y0+4 y0+4];
patch(x,y,[0.3 0.2 0.45])
end
so shape gets a string
for example shape='vav';
but when i use f=str2func(shape)
and i call f(x0,y0) it doesn't work.
how can i fix it? and what is wrong with this way?
Thanks!!
More code:
draw(shape)
function[]= draw(shape)
x0=5;
y0=20;
set(myfig,'KeyPressFcn',#keyPressed);
function [] = keyPressed(~,event)
switch event.Key
case 's'
y0=moveDown(y0);
cla(PlayAx)
f=str2func(shape);
f(x0,y0);
if y0==0
draw(shape)
end
and the error for example when shape gets the value 'vav' it gets also other value but it works for none of them
Undefined function 'vav' for input arguments of type 'double'.

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.

integral error (first input argument must be function handle.)

I want to use an integral over a vector but I will see an error for sys_eff which is " First input argument is not function handle."
I will be glad to have your guide and thanks in advance.
I should mention that all vectors have the same ize as 345600.
function [ P_loss,time_eff, sys_eff ] = final( Pmpp, Pl_inv, Pl_bat_inv, Pl_bat_r )
j=length(Pmpp);
for t=1:j;
P_loss(t)= Pl_inv(t) + Pl_bat_inv(t) + Pl_bat_r(t);
time_eff(t)= P_loss(t)/Pmpp(t);
end
sys_eff=integral(time_eff,0,345600);
end
As from the error message, the first input you provided to the function integral (i.e. time_eff) is not a function handle, but a vector.
If you want to make a numeric integral of the function use the function trapz
sys_eff=trapz(t,time_eff)
if t is your integration variable.

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.

Giving default values to only some function variables in Matlab

I made a Matlab function
function foo(argone, argtwo)
The begining of the function allow to have default choices for those variables if the function is called only with one or even zero arguments
function foo(argone, argtwo)
if(~exist('argone','var'))
argone = defaultargone;
end
if(~exist('argtwo', 'var'))
argtwo = defaultargtwo;
end
... % Rest of the code
We can call the function as
foo() % Default values are assigned to argone and argtwo
foo(myargone) % Default value given to argtwo
foo(myargone, myargtwo) % No default values are used
But how to be able to give default value to argone only?
If function is called with
foo(~, myargtwo)
no default values are used; argone get the null value (that is not the default value)
Thank you for your help
An alternate way would be to include the option for handling an empty input:
function foo(argone, argtwo)
if ~exist('argone','var')||isempty(argone)
argone = defaultargone;
end
if ~exist('argtwo','var')||isempty(argtwo)
argtwo = defaultargtwo;
end
Then any of these should work:
foo()
foo([],[])
foo(argone)
foo([], argtwo)
The language itself does not support such inputs. A common workaround uses parameter value pairs.
Usange would be
foo('myargone',1, 'myargtwo',2)
foo('myargtwo',3)
foo('myargone',4)
In your function, you have to use varargin and the input parser