Partial Function Evaluation in MATLAB

ぃ、小莉子 提交于 2019-12-29 06:40:25

问题


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

回答1:


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.




回答2:


I am pretty sure that a nested function can be used with fminsearch. I don't know specifically about Newtons method, but my guess is that there is no problem.



来源:https://stackoverflow.com/questions/9154271/partial-function-evaluation-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!