Anonymous function with vector instead of multiple inputs

3 次查看(过去 30 天)
Hello everyone,
I have the following example code that creates an array of functions. The size of the array and the number of input arguments varies. I would like to evaluate the functions as explained in the comments in the code.
Thanks for any help,
Stephan
%
%%Input
N = 3;
%---------- Is this efficiently preallocated? -----------------------------
variables = cell(N,1);
fct_handle = cell(N,1);
myfunction = cell(N,1);
%--------------------------------------------------------------------------
%%Define multidimensional input
for j = 1:N
variables{j} = sym(sprintf('x_%d',j));
end
%%Define anonymous function
for j = 1:N
temp = 0;
for k = 1:N
temp = temp + variables{k};
end
myfunction{j} = temp;
fct_handle{j} = matlabFunction(myfunction{j});
end
%%Evaluation of function
% I want to evaluate the anonymous functions like this...
input = randn(1,N);
fct_handle{1}(input(1),input(2),input(3));
fct_handle{2}(input(1),input(2),input(3));
fct_handle{3}(input(1),input(2),input(3));
%--------------------- Unforunately this does not work --------------------
for j = 1:N
fct_handle{j}(input);
end
%--------------------------------------------------------------------------

采纳的回答

David Ding
David Ding 2017-10-19
Hi Stephan,
First of all the use of "cell" function is perfectly fine. With regards to the error you are seeing, it is because the way your anonymous function is defined, it expects three input arguments. I understand that you have an input vector which contains three elements. However, you would still need to "split" the elements up when you call the anonymous function. Something like this:
my_anon_func(input(1), input(2), input(3))
Thanks,
David

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by