How to evaluate inline functions each variable at once?

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!

 채택된 답변

Walter Roberson
Walter Roberson 2017년 5월 14일
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

Thank you guys! I know that inline functions will be discontinued, however it seemed the fastest way to do it. Reading other forums, I got to know that they certainly will let your code run slower and you might get lost with so many variables on the workspace. I will try changing everything to anonymous functions from now on!
Lucas Carvalho
Lucas Carvalho 2017년 5월 14일
편집: Lucas Carvalho 2017년 5월 14일
Walter Robertson, the problem I'm getting now is to have these components of vector X into the anonymous functions. The number of components of X will depend on the user input, it can be any finite number, so I can't define the vector X manually. How can I use the command X=[x1, x2, x3, ..., xn], where all these variables are symbolic? And how can I put this vector as the anonymous function input, instead of writing each of its components? (example: f(x1,x2,...,xn)=f(X), where X=[x1,x2,...,xn])
N = 4;
X = sym('x', [1, N]);
Thank you very much indeed! My code is now working perfectly!

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

추가 답변 (1개)

Stephen23
Stephen23 2017년 5월 14일
편집: Stephen23 2017년 5월 14일
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.

카테고리

도움말 센터File Exchange에서 Function Creation에 대해 자세히 알아보기

질문:

2017년 5월 13일

댓글:

2017년 5월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by