MATLAB Answers

Evaluating function handle with array input arguments

32 views (last 30 days)
M Al Mamun
M Al Mamun on 11 Mar 2020
Edited: Peter on 11 Mar 2020
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.

  0 Comments

Sign in to comment.

Answers (1)

Peter
Peter on 11 Mar 2020
Edited: Peter on 11 Mar 2020
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

  0 Comments

Sign in to comment.


Translated by