Evaluating function handle with array input arguments

조회 수: 23 (최근 30일)
M Al Mamun
M Al Mamun 2020년 3월 11일
편집: Peter O 2020년 3월 11일
Hi all, I am facing some trouble while working with function handle. It is as below.
I have a function handle of 3 different variables given below.
f=@(x1,x2,x3) x1^2+2*x2+x3;
Now, we can easily evaluate the value of f at any point, for example, (1,2,3) by f(1,2,3).
But if the number of varialbes becomes very high and they change in every iteration, we put them into an array to use easily and efficiently.
For the above example, if we put the three varialbe values into an array x=[1 2 3], then f(x) doesn't work. But f(x(1), x(2), x(3)) works like the first case.
Is there any other easy way to evaluate the function value? Thank you.

답변 (1개)

Peter O
Peter O 2020년 3월 11일
편집: Peter O 2020년 3월 11일
Are you specifically looking at a binomial expansion? If so, there's a trick for composing that.
For a generalized "raise this number to this value and multiply by this coefficient", you can still use arrays, and take advantage of elementwise operators. In general, elementwise operators are what will enable you to use arrays in a function handle.
For your example above:
p1 = [2,1,1];
c1 = [1,2,1];
x1 = [1,2,3];
f=@(x,p,c) sum(c.*(x.^p));
f(x1,p1,c1)
8
In my experience, the utility of anonymous functions is best for small functions without much logic, or as handlers for binding specific values to more generalized functions. If you need a loop or specialty access logic, it's often simpler in the long run to create a dedicated function.
A related tool for arrays in functions is arrayfun, which applies a function to all entries in an array.
arrayfun(@(x) x+2, x1)
[3, 4, 5]
It can take multiple inputs as well, allowing us to replicate the above in a slightly different way:
sum (arrayfun(@(x,p,c) c*x^p, x1,p1,c1))
8

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by