Clear Filters
Clear Filters

How to evaluate inline functions each variable at once?

4 views (last 30 days)
Hello guys! Let's say I have two symbolic functions:
f1 = x1^2+x2;
f2 = x3^2;
When I transform both to inline functions, f1 will be dependent of x1 and x2 and f2 of x3. I have a vector where I store the values for x1,x2,x3. How can I use the inline function with the elements of this vector without having too many or not enough arguments? Can I evaluate the functions one element at once?
Thanks in advance!

Accepted Answer

Walter Roberson
Walter Roberson on 14 May 2017
syms x1 x2 x3
f1 = x1^2+x2;
f2 = x3^2;
X = [x1, x2, x3]
nf1 = matlabFunction(f1, 'vars', {X});
nf2 = matlabFunction(f2, 'vars', {X});
Unless you are specifically required to use inline functions by the wording of an assignment (or by a supervisor), you should avoid doing so now. inline functions were fine in MATLAB 4 but early in MATLAB 5, 20 years ago, they were replaced by anonymous functions.
  4 Comments
Lucas Carvalho
Lucas Carvalho on 15 May 2017
Thank you very much indeed! My code is now working perfectly!

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 14 May 2017
Edited: Stephen23 on 14 May 2017
The simplest solution is to use indexing, and define each function to accept a vector input. Here I used function handles because inline functions are being deprecated.
>> f1 = @(x)x(1)^2+x(2);
>> f2 = @(x)x(3)^2;
>> f1(1:3)
ans =
3
>> f2(1:3)
ans =
9
Note that you can convert from symbolic to function handle using matlabfunction.

Categories

Find more on Function Creation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!