Is there an idiomatic way to bind variables in a MATLAB function? It seems like it would be fairly common to create a function, bind a few arguments, then pass the new function to an optimizer of some sort (in my case, a Newton solver). It doesn't look like the variable scoping rules permit a solution with nested or inline functions. Should I simply create a class? It doesn't seem like MATLAB has first-class function objects, is this correct? My search kung-fu is coming up short. Thanks!
As an example, suppose I want to find the roots of f(c,x)=x^3+cx^2+2x+3 for various values of the parameter c. I have a Newton's method solver which takes a function of one variable, not two. So I loop over various values of c, then pass the bound function to the solver.
for c=1:10 g=f(c); % somehow bind value of c seed=1.1; % my guess for the root of the equation root=newton(g,seed); % compute the actual root end
You can do it like this:
f = @(c,x)( @(x)(x^3+c*x^2+2*x+3) ); for c=1:10 g=f(c); % g is @(x)(x^3+c*x^2+2*x+3) for that c .... end
The key is the first line: it's a function that returns a function.
I.e., it returns @(x)(x^3+c*x^2+2*x+3)
, with the value of c
bound in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With