Anonymous function with vector instead of multiple inputs

4 vues (au cours des 30 derniers jours)
Stephan
Stephan le 16 Oct 2017
Commenté : Stephan le 25 Oct 2017
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
%--------------------------------------------------------------------------

Réponse acceptée

David Ding
David Ding le 19 Oct 2017
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
  1 commentaire
Stephan
Stephan le 25 Oct 2017
Thanks for your comment! I see, I have to rewrite my code...

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Debugging and Analysis dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by