Anonymous function with vector instead of multiple inputs
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Stephan
el 16 de Oct. de 2017
Comentada: Stephan
el 25 de Oct. de 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
%--------------------------------------------------------------------------
0 comentarios
Respuesta aceptada
David Ding
el 19 de Oct. de 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
Más respuestas (0)
Ver también
Categorías
Más información sobre Workspace Variables and MAT-Files en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!