Is possible to store anonymous functions in an array?
I'm receiving two different errors for different approaches:
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'
You can put them into a cell array:
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)
}
Access the individual anonymous functions like so:
>> f{3}
ans =
@(x) -cos (x)
You can even pass arguments to a specific function in the array:
>> f{2}(pi/2)
ans = -1