Question

What I try to do is keep a cell-array of function handles, and then call one of them in a loop. It doesn't work, and it seems to me that what I get is just a 1x1 cell array, and not the function handle within it.

I am not fixed on using cell arrays, so if another collection works it's fine by me.

This is my code:

func_array = {@(x) x, @(x) 2*x }
a = func_array(1) %%% a = @(x) x
a(2) %%% (error-red) Index exceeds matrix dimensions.
a(0.2) %%% (error-red) Subscript indices must either be real positive integers or
logicals.

Thank you Amir

Was it helpful?

Solution

The problem is in this line:

a = func_array(1)

you need to access the content of the cell array, not the element.

a = func_array{1}

and everything works fine. The visual output in the command window looks the same, which is truly a little misleading, but have a look in the workspace to see the difference.

As mentioned by chappjc in the comments, the intermediate variable is not necessary. You could call your functions as follows:

func_array{2}(4)    %// 2*4

ans =  8

Explanation of errors:

a(2) %%% (error-red) Index exceeds matrix dimensions.

a is still a cell array, but just with one element, therefore a(2) is out of range.

a(0.2) %%% (error red) Subscript indices must either be real positive ...

... and arrays can't be indexed with decimals. But that wasn't your intention anyway ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top