如何将匿名函数分配给 Octave 中的数组?

How to assign anonymous functions to an array in Octave?

是否可以在数组中存储匿名函数

我收到两个不同方法的不同错误:

f(1) = @(x) cos(x)
f(2) = @(x) -sin(x)
f(3) = @(x) -cos(x)
f(4) = @(x) sin(x)

error: operator =: no conversion for assignment of 'function handle' to indexed 'scalar'
f = [@(x) cos(x), @(x) -sin(x), @(x) -cos(x), @(x) sin(x)]

error: octave_base_value::resize (): wrong type argument 'function handle'

您可以将它们放入元胞数组中:

f{1} = @(x) cos(x);
f{2} = @(x) -sin(x);
f{3} = @(x) -cos(x);
f{4} = @(x) sin(x);

>> f
f =
{
  [1,1] =

@(x) cos (x)

  [1,2] =

@(x) -sin (x)

  [1,3] =

@(x) -cos (x)

  [1,4] =

@(x) sin (x)

}

像这样访问各个匿名函数:

>> f{3}
ans =

@(x) -cos (x)

您甚至可以将参数传递给数组中的特定函数:

>> f{2}(pi/2)
ans = -1