Matlab Functions and arguments - matlab

Suppose we have a function defined as:
function(f, df, x0)
where f is a function, df is its derivative, and x0 is an initial point. How do we defined f on the command line? Do you use an inline definition? What about df and x0? What if df is a gradient? Also if x0 is an ordered pair, how do you define it in the command line?

To pass a function as a variable, you need to use a function handle. A simple way to demonstrate this is to use a function handle to an anonymous function. A simple anonymous function can be defined as follows:
handle = #(arglist)anonymous_function
So, to make an anonymous function that adds 2 numbers, you could do something like the following:
f = #(a,b)a+b;
You can use this like any other function
>> f(1,2)
ans =
3
If df is just a simple numeric value, it can be defined as follows:
df = 0.4
To define a pair of values, you could do it like so:
X0=[1 2]
Finally, you can put it all together with this example function (put this in a file called myfunc) . . .
function out = myfunc(f,df,x0)
out = df * f(x0(1), x0(end));
Is this what you want? I was slightly confused by "x0 is an ordered pair".

Related

Finding parameter names from anonymous function

I want to be able to find the parameter names of an anonymous function in Matlab.
I tried to see if there was any information about the parameter names in the functions() command, but to no avail.
Say I have an anonymous function f:
f = #(x, y) x^2 + y^2
I need to be able to find the parameter names 'x' and 'y' from this equation. Is there a built in method in Matlab which can do this? Or would I somehow have to parse the function to receive the parameter names?
The function field in the output of functions (or equivalently the output of func2str) gives the function definition as a string. You then use a regular expression to match each sequence of one or more non-), non-, characters that are between a #( or , and a , or ):
s = functions(f);
inputVarNames = regexp(s.function, '(?<=(,|#\())[^\)]+?(?=(,|\)))', 'match');

Passing parameters to function handle in bagOfFeatures function

Lets say we have a custom extractor function
[features,featureMetrics] = exampleBagOfFeaturesExtractor(img,param1, param2)
I want to call bagOfFeatures function and pass custom extractor function:
extractorFcn = #exampleBagOfFeaturesExtractor;
bag = bagOfFeatures(imgSets,'CustomExtractor',extractorFcn)
In exampleBagOfFeaturesExtractor function I want to use different local descriptors extractor depending on param1.
How do I pass param1 to exampleBagOfFeaturesExtractor?
What is the best way to use different local descriptors in my custom extractor function?
Thank you for your help!
Edit
This is the custom extractor function I am currently using:
function [features,featureMetrics] = exampleBagOfFeaturesExtractor(img,param1,param2)
keypoint_detector = cv.FeatureDetector(param1);
descriptor_extractor = cv.DescriptorExtractor(param2);
kpts = keypoint_detector.detect(img);
[ features, kpts ] = descriptor_extractor.compute(img, kpts);
featureMetrics=ones(1,size(features,1))/size(features,1);
end
The expected kind of functions that the bagOfFeatures function requires can only be a single input, namely the input image. Therefore, if you want to create a custom feature extractor where you can vary the parameters, you will need to first create the parameters, then create an anonymous function that captures these parameters via lexical closure. This means that when you create the anonymous function, make sure the parameters are created so that when you reference them in your anonymous function, they capture the most up to date version of the parameters prior to creating the function.
Therefore, assuming param1 and param2 already exist in your workspace, create a function like so:
% Create param1 and param2 here
param1 = ...;
param2 = ...;
extractorFcn = #(img) exampleBagOfFeaturesExtractor(img, param1, param2);
This creates an anonymous function that takes in a single input - your image. param1 and param2 are thus captured in your function, so the state of the variables is recorded and are made available within the anonymous function. Also note that the function doesn't take in additional inputs, only the input image. You can then call bagOfFeatures as normal. However, should you want to change param1 or param2, not only will you have to change these parameters, but you must re-declare the anonymous function again so that the latest stage of the variables is recaptured.
As a quick example, suppose I've created an anonymous function like so:
x = 5;
y = #(t) t + x;
This function y takes the current state of x and adds it with a variable t. For now, this acts like how we expect it:
>> x = 5;
>> y = #(t) t + x;
>> y(6)
ans =
11
We put in the value 6 and we get 11. If we try and change x then call y, it will not change this in the function as it captured the state of the variable before you created the function:
>> x = 10;
>> y(6)
ans =
11
Therefore, if you want to change the parameters, you must also re-declare the function again before calling bagOfFeatures, so:
param1 = ...; % Change this to something new
param2 = ...; % Change this if you like as well
extractorFcn = #(img) exampleBagOfFeaturesExtractor(img, param1, param2);
In MATLAB terms, these variables persist in the anonymous function. You can read more about it here: https://www.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html#f4-71621

Difference between matlab function 'handle' and python function 'object'

It was suggested in this comment that there is a difference between how Matlab and Python pass around functions. From what I can tell by looking and using the two, there is no difference between the two, but maybe I'm missing something?
In Matlab, you would create a quick function handle like this:
fun = #(x) x.^2 + 1;
In Python, using a lambda function, you could create a similar function like this:
def fun(x):
return x^2
In both languages, it's possible to send the term 'fun' to another function as an argument - but the commenter I linked to insinuated that they are not the same and/or need to be used differently.
What am I missing?
The first comment seems to simply reiterate the idea that you can pass a MATLAB function handle as an argument (although the answer didn't state anything that would make me think otherwise). The second comment seemed to interpret this to mean that the first commenter thought that you couldn't do this in Python and responded to state that you can use either a lambda or pass the function directly.
Regardless, assuming that you use them correctly, a function handle in MATLAB is functionally equivalent to using either a lambda or function object as an input argument in Python.
In python, if you don't append the () to the end of the function, it doesn't execute the function and instead yields the function object which can then be passed to another function.
# Function which accepts a function as an input
def evalute(func, val)
# Execute the function that's passed in
return func(val)
# Standard function definition
def square_and_add(x):
return x**2 + 1
# Create a lambda function which does the same thing.
lambda_square_and_add = lambda x: x**2 + 1
# Now pass the function to another function directly
evaluate(square_and_add, 2)
# Or pass a lambda function to the other function
evaluate(lambda_square_and_add, 2)
In MATLAB, you have to use a function handle because MATLAB attempts to execute a function even if you omit the ().
function res = evaluate(func, val)
res = func(val)
end
function y = square_and_add(x)
y = x^2 + 1;
end
%// Will try to execute square_and_add with no inputs resulting in an error
evaluate(square_and_add)
%// Must use a function handle
evaluate(#square_and_add, 2)

Passing command lines to function to evaluate in Matlab

I have a function which is very open-ended that I use in several different applications. Instead of changing it everytime, I would like to pass several command lines as input for the function to evaluate using something like the eval function.
Thus, for example, my argument would be:
str={'a=32;
b=a+3*a^2+pi;
c=sin(a)+cos(b)^2;'}
then I could call the function with str as an argument:
x=func(str)
these lines would be evaluated inside the function
how?
Thanks alot!
I think #Daniel is right that function handles are the way forward. Based on your example, this is how you'd do it:
function x = testfun( a, bfun, cfun )
b = bfun(a);
c = cfun(a, b);
x = a + b + c;
end
Then you'd call it like this:
x = testfun( 32, #(a)(a+3*a^2+pi), #(a,b)(sin(a)+cos(b)^2) );

Substitute s in transfer function

I need to substitute a value for s in a transfer function. For example:
G(s)= 1/ (s+3)
I need to substitute
s = -2.118 +2.221j
What code should I use for this?
PS: Unfortunately, I only have control system toolbox in MATLAB.
What's wrong with saving m-file with
function g = transferFun( s )
g = 1 ./ ( s + 3 )
And then calling the function
>> transferFun( -2.118 + 2.221*j )
As shai mentioned you can simply create an m file with the function.
However, if you are just doing some quick calculations here is a way to just do it on the command line. You can define an anonymous function like this:
G = #(s) 1/(s+3)
Now you can simply call it like this:
G(-2.118 +2.221j)
Note that Matlab is case sensitive.