Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

functional programming - Partial Function Evaluation in MATLAB

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...