Anonymous function with vector instead of multiple inputs
조회 수: 4 (최근 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
%--------------------------------------------------------------------------
댓글 수: 0
채택된 답변
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 Center 및 File Exchange에서 Workspace Variables and MAT-Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!