MATLAB中的部分函数评估 [英] Partial Function Evaluation in MATLAB

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

问题描述

在MATLAB函数中是否存在绑定变量的惯用方法?看起来创建一个函数,绑定几个参数,然后将这个新函数传递给某种优化器(在我的例子中,是一个牛顿求解器)是相当普遍的。它看起来不像变量范围规则允许使用嵌套或内联函数的解决方案。我应该简单地创建一个班级吗?似乎MATLAB没有一流的函数对象,这是正确的吗?我的搜寻功夫即将到来。作为一个例子,假设我想找到f(c,x)= x ^ 3 + cx ^ 2 + 2x + 3对于各种值的根的参数c。我有一个牛顿方法求解器,它只接受一个变量的函数,而不是两个。所以我循环了c的各种值,然后将绑定函数传递给求解器。

  for c = 1:10 
G = F(C); %以某种方式绑定c
seed = 1.1的值; %我猜测方程的根
root = newton(g,seed); %计算实际根目录
结束


解决方案

您可以这样做:

  f = @(c,x)(@(x)(x ^ 3 + c * x ^ 2 + 2 * x + 3)); 

for c = 1:10
g = f(c); %g是@(x)(x ^ 3 + c * x ^ 2 + 2 * x + 3)对于那个c
....
结束

关键是第一行:它是一个返回函数的函数。



Ie ,它返回 @(x)(x ^ 3 + c * x ^ 2 + 2 * x + 3),其值 c 绑定。


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.

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

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