Ami*_*giv 2 arrays matlab anonymous-function
我试图做的是保留一个函数句柄的元胞数组,然后在循环中调用其中一个。它不起作用,在我看来,我得到的只是一个 1x1 元胞数组,而不是其中的函数句柄。
我不固定使用单元格数组,所以如果另一个集合工作对我来说很好。
这是我的代码:
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.
Run Code Online (Sandbox Code Playgroud)
谢谢阿米尔
问题出在这一行:
a = func_array(1)
Run Code Online (Sandbox Code Playgroud)
you need to access the content of the cell array, not the element.
a = func_array{1}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Explanation of errors:
a(2) %%% (error-red) Index exceeds matrix dimensions.
Run Code Online (Sandbox Code Playgroud)
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 ...
Run Code Online (Sandbox Code Playgroud)
... and arrays can't be indexed with decimals. But that wasn't your intention anyway ;)