필터 지우기
필터 지우기

Anonymous function with vector instead of multiple inputs

조회 수: 3 (최근 30일)
Stephan
Stephan 2017년 10월 16일
댓글: Stephan 2017년 10월 25일
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
  댓글 수: 1
Stephan
Stephan 2017년 10월 25일
Thanks for your comment! I see, I have to rewrite my code...

댓글을 달려면 로그인하십시오.

추가 답변 (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