MATLAB 中的偏函数求值 [英] Partial Function Evaluation in MATLAB

查看:22
本文介绍了MATLAB 中的偏函数求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种惯用的方法来绑定 MATLAB 函数中的变量?创建一个函数,绑定几个参数,然后将新函数传递给某种优化器(在我的例子中是牛顿求解器)似乎是相当普遍的.看起来变量作用域规则不允许使用嵌套或内联函数的解决方案.我应该简单地创建一个类吗?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!

举个例子,假设我想为参数 c 的各种值找到 f(c,x)=x^3+cx^2+2x+3 的根.我有一个牛顿法求解器,它采用一个变量的函数,而不是两个.所以我循环遍历 c 的各种值,然后将绑定函数传递给求解器.

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

推荐答案

你可以这样做:

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.

即,它返回 @(x)(x^3+c*x^2+2*x+3),值为c 绑定在.

I.e., it returns @(x)(x^3+c*x^2+2*x+3), with the value of c bound in.

这篇关于MATLAB 中的偏函数求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆