我可以在匿名函数中重用表达式的结果吗?

kro*_*chi 2 matlab anonymous-function

我有一个@(x) sqrt(x) + 1./sqrt(x) - 3想要传递给另一个函数的匿名函数,例如

fsolve(@(x) sqrt(x) + 1./sqrt(x) - 3, 3)
Run Code Online (Sandbox Code Playgroud)

想象一下,的参数sqrt稍微复杂一点,因此sqrt(...)调用的计算量很大-是否有可能创建一个先计算(在此简单示例中)sqrt(x)然后将结果res用于计算的匿名函数res + 1/res - 3

还是只能使用正常功能对其进行编程?

Han*_*rse 6

如果您对嵌套匿名函数的想法进入“没有中间步骤的单个匿名函数中的所有内容”(即中间匿名函数)的方向,那么我想不出解决方案,因为您必须以某种方式将值“存储”到防止其重新计算。因此,我的想法如下:

% Original function
orig = @(x) sqrt(x) + 1./sqrt(x) - 3;

% Complicated inner function
inner = @(x) sqrt(x);

% Actual function
func = @(y) y + 1./y - 3;

% Function wrapper
wrapper = @(z) func(inner(z));

% Some small tests
X = 1:10;
orig(X)
wrapper(X)

ans =
  -1.000000  -0.878680  -0.690599  -0.500000  -0.316718  -0.142262   0.023716   0.181981   0.333333   0.478505

ans =
  -1.000000  -0.878680  -0.690599  -0.500000  -0.316718  -0.142262   0.023716   0.181981   0.333333   0.478505
Run Code Online (Sandbox Code Playgroud)

至少从我的角度来看,复杂的内部函数仅被评估一次。