Determine number of variables of a inline function in Matlab - matlab

I would like to write a function like this:
function foo(goo,...)
if( goo is a function of two variables )
% do something
else
% do something else
end
end
Is there any way I can get the number of variables of a inline function (or of an anonymous function?). To make it more clear:
f = inline('x + y')
g = inline('x')
I want to be able to distinguish that f is a function of two variables and g of 1 variable

EDIT
After I answered this, a better strategy has been found: Just use nargin; see #k-messaoudi's answer.
For inline functions:
According to inline's help:
INLINE(EXPR) constructs an inline function object from the MATLAB expression contained in the string EXPR. The input arguments are automatically determined by searching EXPR
for variable names (see SYMVAR).
Therefore: call symvar and see how many elements it returns:
>> f = inline('x + y');
>> g = inline('x');
>> numel(symvar(f))
ans =
2
>> numel(symvar(g))
ans =
1
For anonymous functions:
First use functions to get information about the anonymous function:
>> f = #(x,y,z) x+y+z;
>> info = functions(f)
info =
function: '#(x,y,z)x+y+z'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
Now, again use symvar on info.function:
>> numel(symvar(info.function))
ans =
3

define your variables : syms x1 x2 x3 .... xn;
define your function : f = inline(x1 + x2 + sin(x3) + ... );
number of input argument : n_arg = nargin(f)
number of output argument : n_arg = nargout(f)

Related

MATLAB anonymous function detailed workings [duplicate]

MATLAB stores variables along with anonymous functions. Here is an example of how this works from the documentation.
Variables in the Expression:
Function handles can store not only an expression, but also variables
that the expression requires for evaluation.
For example, create a function handle to an anonymous function that
requires coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = #(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the
function handle includes those values. The values persist within the
function handle even if you clear the variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000
Supposedly, the values of a b and c are stored with the function even when it's saved and reloaded from a mat file. In practice, I've found that these values do not persist, especially if the code that originally created the function is edited.
Is there a way to define the function handle in terms of the numeric values of the variables? I would like something of the form
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = #(x) a*x.^2 + b*x + c
parabola = #(x) a*x.^2+b*x+c
>> parabola2 = forceEval(parabola)
parabola2 = #(x) 1.3*x.^2+.2x+30
EDIT: Perhaps my problem is with the file association, but when I edit the file that I originally defined the anonymous function in, I get an error that looks like:
Unable to find function #(ydata)nr/(na*dt)*normpdf(ydata,mu(j),s(j))./normpdf(ydata,mu_a(j),s_a(j)) within
C:...\mfilename.m. (where I've changed the name of my mfile to mfilename)
My usual solution to this kind of stuff has been to use func2str() to remove the file dependency, but this also strips out the workspace information including the parameter values. So I would like to force all the parameters to take on their numerical values in the function definition.
The values are stored in the function. As I've demonstrated in different answers before, you can check this with the functions command:
>> a = 1.3; b = .2; c = 30;
>> parabola = #(x) a*x.^2 + b*x + c;
>> x = 1;
>> y = parabola(x)
y =
31.5
>> clear a b c
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
Even when you save the handle to disk:
>> save parabolaFun.mat parabola
>> clear parabola a b c
>> load parabolaFun.mat parabola
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
And you can simplify the creation of a parabola handle like this:
function p = makeParabola(a,b,c)
p = #(x) a*x.^2 + b*x + c;
end
There are certain caveats:
You can save and load function handles in a MAT-file using the MATLABĀ® save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
Any of the files that define the function have been moved, and thus no longer exist on the path stored in the handle.
You load the function handle into an environment different from that in which it was saved. For example, the source for the function either does not exist or is located in a different folder than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
Hence, if you create the handle from a file-backed function (not a script, that's OK), and then modify or delete the file, the handle will become invalid.
Anonymous functions capture the values of all variables involved in the expression. If you want to see the environment workspace captured, use functions as #chappjc showed in his answer.
Now you gotta be careful about the type of variables used in the anonymous function (think value-type vs. handle-type).
All native types (numerics, logicals, structs, cells, etc..) are captured by-value not by-reference. Example:
x = magic(4);
f = #() x; % captures matrix x
x(1) = 1 % modify x
xx = f() % change not reflected here
Compare that to using handle-class types (e.g containers.Map):
x = containers.Map('KeyType','char', 'ValueType','double');
f = #() x; % captures handle-class object x
x('1') = 1; % modify map
keys(x) % changed
keys(f()) % also changed!
f() == x % compare handle equality, evaluates to true
a = 1.3, b = 0.2, c = 30;
parabola = eval(['#(x) ', num2str(a), '*x^2 + ', num2str(b), '*x + ', num2str(c)]);

Use value of variable instead of its name lambdas matlab

How to use value of variable instead of its name during the description of a lambda expression? This is part of my code:
eq1 = k*x1+b==y1;
eq2 = k*x2+b==y2;
sol=solve([eq1,eq2],[k,b]);
linEq1 = #(x) sol.k*x+sol.b;
if (defY<linEq1(defX))
ineq = #(x,y) y<=sol.k*x+sol.b;
else
ineq = #(x,y) y>=sol.k*x+sol.b;
end
I need to use value of sol.b and sol.k in lambda expression instead of their names. When I use function which contains this code I can see in workspace:
y<=sol.k*x+sol.b
instead of
y<=5x+3
for example.
I tried to condense your code a bit. Please provide a minimal working example next time.
a = 5
b = 3
y = #(x) a*x + b % note that a and b are evaluated at definition
a = 4
y(1) % this is 8 (even though we changed the value of a)
% but if you really really want to do what you are asking, this is how:
eval(['y = #(x) ' num2str(a) '*x + ' num2str(b)]) % yields y = #(x)4*x+3

Force evaluation of variables in MATLAB anonymous function

MATLAB stores variables along with anonymous functions. Here is an example of how this works from the documentation.
Variables in the Expression:
Function handles can store not only an expression, but also variables
that the expression requires for evaluation.
For example, create a function handle to an anonymous function that
requires coefficients a, b, and c.
a = 1.3;
b = .2;
c = 30;
parabola = #(x) a*x.^2 + b*x + c;
Because a, b, and c are available at the time you create parabola, the
function handle includes those values. The values persist within the
function handle even if you clear the variables:
clear a b c
x = 1;
y = parabola(x)
y =
31.5000
Supposedly, the values of a b and c are stored with the function even when it's saved and reloaded from a mat file. In practice, I've found that these values do not persist, especially if the code that originally created the function is edited.
Is there a way to define the function handle in terms of the numeric values of the variables? I would like something of the form
>> a = 1.3;
>> b = .2;
>> c = 30;
>> parabola = #(x) a*x.^2 + b*x + c
parabola = #(x) a*x.^2+b*x+c
>> parabola2 = forceEval(parabola)
parabola2 = #(x) 1.3*x.^2+.2x+30
EDIT: Perhaps my problem is with the file association, but when I edit the file that I originally defined the anonymous function in, I get an error that looks like:
Unable to find function #(ydata)nr/(na*dt)*normpdf(ydata,mu(j),s(j))./normpdf(ydata,mu_a(j),s_a(j)) within
C:...\mfilename.m. (where I've changed the name of my mfile to mfilename)
My usual solution to this kind of stuff has been to use func2str() to remove the file dependency, but this also strips out the workspace information including the parameter values. So I would like to force all the parameters to take on their numerical values in the function definition.
The values are stored in the function. As I've demonstrated in different answers before, you can check this with the functions command:
>> a = 1.3; b = .2; c = 30;
>> parabola = #(x) a*x.^2 + b*x + c;
>> x = 1;
>> y = parabola(x)
y =
31.5
>> clear a b c
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
Even when you save the handle to disk:
>> save parabolaFun.mat parabola
>> clear parabola a b c
>> load parabolaFun.mat parabola
>> y = parabola(x)
y =
31.5
>> fi = functions(parabola)
fi =
function: '#(x)a*x.^2+b*x+c'
type: 'anonymous'
file: ''
workspace: {[1x1 struct]}
>> fi.workspace{1}
ans =
a: 1.3
b: 0.2
c: 30
And you can simplify the creation of a parabola handle like this:
function p = makeParabola(a,b,c)
p = #(x) a*x.^2 + b*x + c;
end
There are certain caveats:
You can save and load function handles in a MAT-file using the MATLABĀ® save and load functions. If you load a function handle that you saved in an earlier MATLAB session, the following conditions could cause unexpected behavior:
Any of the files that define the function have been moved, and thus no longer exist on the path stored in the handle.
You load the function handle into an environment different from that in which it was saved. For example, the source for the function either does not exist or is located in a different folder than on the system on which the handle was saved.
In both of these cases, the function handle is now invalid because it is no longer associated with any existing function code. Although the handle is invalid, MATLAB still performs the load successfully and without displaying a warning. Attempting to invoke the handle, however, results in an error.
Hence, if you create the handle from a file-backed function (not a script, that's OK), and then modify or delete the file, the handle will become invalid.
Anonymous functions capture the values of all variables involved in the expression. If you want to see the environment workspace captured, use functions as #chappjc showed in his answer.
Now you gotta be careful about the type of variables used in the anonymous function (think value-type vs. handle-type).
All native types (numerics, logicals, structs, cells, etc..) are captured by-value not by-reference. Example:
x = magic(4);
f = #() x; % captures matrix x
x(1) = 1 % modify x
xx = f() % change not reflected here
Compare that to using handle-class types (e.g containers.Map):
x = containers.Map('KeyType','char', 'ValueType','double');
f = #() x; % captures handle-class object x
x('1') = 1; % modify map
keys(x) % changed
keys(f()) % also changed!
f() == x % compare handle equality, evaluates to true
a = 1.3, b = 0.2, c = 30;
parabola = eval(['#(x) ', num2str(a), '*x^2 + ', num2str(b), '*x + ', num2str(c)]);

Using inline function with constant arguments in MATLAB

This is a part of my code.
clear all;
clc;
p = 50;
t = [-6 : 0.01 : 6];
f = inline('(t+2).*sin(t)', 't')
v = inline('3*f(p*t+2)','t','f','p')
plot(t,f(t));
v(t,f,p);
figure;
plot(t,v(t,f,p));
Here I have two questions.
Why I have to pass p into the function v even though p is a constant which has already declared ?
How I can get an expression for v completely in terms of t as 3*[(50*t+2)*sin(50*t+2)] or in its simplified form ?
Update
This is an update for the second question
Let
f(x) = 1 + x - x^2
g(x) = sin(x)
If I give f(g(x)), I wanna get the output in words, like this
f(g(x)) = (cos(X))^2 + sin(x)
not in numerical value. Is there any function capable to do that?
1) Why do I have to pass p to v even though p is a constant which has already been declared?
Well, a MATLAB's inline function object has an eval wrapper, so the only variables in its scope are those which were automatically captured from the expression or explicitly specified.
In other words, if you want v to recognize p, you have no other option but declaring it when creating the inline object and passing it to v explicitly. The same goes for f as well!
2) How I can get an expression for v completely in terms of t as 3*[(50*t+2)*sin(50*t+2)] or in its simplified form?
Use anonymous functions, like Shai suggested. They are more powerful, more elegant and much faster. For instance:
v = #(t)(3*(50*t+2)*sin(50*t+2))
Note that if you use a name, which is already in use by a variable, as an argument, the anonymous function will treat it as an argument first. It does see other variables in the scope, so doing something like g = #(x)(x + p) is also possible.
EDIT #1:
Here's another example, this time a function of a function:
x = 1:5;
f = #(x)(x .^ 3); %// Here x is a local variable, not as defined above
g = #(x)(x + 2); %// Here x is also a local variable
result = f(g(x));
or alternatively define yet another function that implements that:
h = #(x)f(g(x)); %// Same result as h = #(x)((x + 2) .^ 3)
result = h(x);
The output should be the same.
EDIT #2:
If you want to make an anonymous function out of the expression string, concatenate the '#(x)' (or the correct anonymous header, as you see fit) to the beginning and apply eval, for example:
expr = '(x + 2) .^ 3';
f = eval(['#(x)', expr]) %// Same result as f = #(x)((x + 2) .^ 3)
Note that you can also do char(f) to convert it back into a string, but you'll have to manually get rid of the '#(...)' part.
EDIT #3:
If you're looking for a different solution, you can explore the Symbolic Toolbox. For example, try:
syms x
f(x) = x + 2
g(x) = x ^ 3
or can also use sym, like so:
f(x) = sym('x + 2');
g(x) = sym('x ^ 3');
Use subs to substitute values and evaluate the symbolic expression.
How about using anonymous functions:
p = 50;
t = -6:0.01:6;
f = #(x) (x+2).*sin(x);
v = #(x) 3*f(p*x+2);
figure;
subplot(1,2,1); plot( t, f(t) ); title('f(t)');
subplot(1,2,2); plot( t, v(t) ); title('v(t)');
Is this what you wanted?
Adding a constant into an inline can be done during its definition.
Instead of
p = 50;
v = inline('3*f(p*t+2)','t','f','p')
You can write
p = 50;
v = inline( sprintf('3*f(%f*t+2)', p), 't','f')

Anonymous Functions calling themselves in MATLAB

As an experiment (and because I'm generating anonymous functions off of user data) I ran the following MATLAB code:
h = #(x) x * x
h = #(x) x * x
h(3)
ans = 9
h = #(x) h(x) + 1
h = #(x)h(x)+1
h(3)
ans = 10
Basically, I made an anonymous function call itself. Instead of acting recursively, MATLAB remembered the old function definition. However, the workspace doesn't show it as one of the variables, and the handle doesn't seem to know it either.
Will the old function be stored behind the scenes as long as I keep the new one? Are there any "gotchas" with this kind of construction?
An anonymous function remembers the relevant part of the workspace at the time of definition, and makes a copy of it. Thus, if you include a variable in the definition of the anonymous function, and change that variable later, it will keep the old value inside the anonymous function.
>> a=1;
>> h=#(x)x+a %# define an anonymous function
h =
#(x)x+a
>> h(1)
ans =
2
>> a=2 %# change the variable
a =
2
>> h(1)
ans =
2 %# the anonymous function does not change
>> g = #()length(whos)
g =
#()length(whos)
>> g()
ans =
0 %# the workspace copy of the anonymous function is empty
>> g = #()length(whos)+a
g =
#()length(whos)+a
>> g()
ans =
3 %# now, there is something in the workspace (a is 2)
>> g = #()length(whos)+a*0
g =
#()length(whos)+a*0
>> g()
ans =
1 %# matlab doesn't care whether it is necessary to remember the variable
>>