2

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

1 Answer 1

5

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 ;)

Sign up to request clarification or add additional context in comments.

1 Comment

This. +1 You can also run the function directly with cascaded indexing like func_array{1}(0.2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.