Charlie Parker
Charlie Parker

Reputation: 5247

How does one pass a function with some fixed argument as an argument in MATLAB

I want to pass a function that has arguments to another function that takes the function handler (pointer) as an argument, but some of the arguments to the function handler need to be fixed. How does one do this in MATLAB?

Concretely I want to minimize a function h(eta) using fminsearch(fun,x0). One obvious issue is that if I pass all the arguments in x0 it will minimize it with respect to all the arguments but that isn't what I want to do. What I really want to do is instead:

enter image description here

I have tried the following and it seems to work as far as I tested it:

function [ h ] = function_returner( x )
%
t = -10000;
h = @(eta)-10*x + t + eta^2;
end

and the script to test it:

h = function_returner(0);
h(3) %-9991
[x,fval,exitflag] = fminsearch(h,[10]) %returns [0, -10000, 1]

returns the correct minimum and the correct value of x at which the minimum is obtained. The thing that I wanted to make sure is that the variables that are fixed of h indeed remain fixed after I returned the function handler. i.e. if h is passed around, how does one make sure that the variables don't change value just because they go into an environment that has the same variables names as in the function handler?

I also wrote:

x = inf;
t = inf;
eta = inf;
h = function_returner(0);
h(3) %-9991
[x,fval,exitflag] = fminsearch(h,[10]) %returns [0, -10000, 1]

and it seems to go unaffected (i.e. it works as I want it to work). But just to be on the safe side, I was hoping there was not a some weird edge condition that this doesn't work.

Upvotes: 3

Views: 73

Answers (1)

user2271770
user2271770

Reputation:

You are worrying unnecessarily. :-) The thing is, when you create an anonymous function, all the outer variables that are used for its definition are frozen, so you don't need to worry that the function will change behavior behind your back via modified parameters. To test this, try this script:

a = 1;
b = 2;

f = @(u,v) u*a + v*b;
x = f(1,1);  %// x is 3 = 1*1 + 1*2

a = 2;
b = 3;

g = @(w) f(w,a)
y = g(1);  %// y is 5 = f(1,2) = 1*1 + 2*2

Upvotes: 3

Related Questions