How to supply different syms values for coefficients of an anonymous function?

조회 수: 1 (최근 30일)
Benjamin
Benjamin 2020년 12월 8일
댓글: Walter Roberson 2020년 12월 11일
Hello everyone
I have a function as f(x) = Ax^2 + Bx, in which A and B are defined as syms. Now I want to re-write/obtain the f(x) function with given A and B, however MATLAB does not recognize A and B as numbers, and recognize them as syms still!
Note that I cannot re-write (create a new function handle) f(x) as suggested here, because in my program this f(x) function is a result of a bunch of other function inversions, integrations, and combinations, so I do not want to stop the program and re-write the function handle again, then give A and B.
I appreicate your suggestions.
Regards.
  댓글 수: 5
Benjamin
Benjamin 2020년 12월 10일
This simply solves the issue. I didn't know the command subs in MATLAB.
Also we could have a vector of syms and subs with values like:
subs(s_fs(fs), [A,B,C], [1,2,3])
Thank you.
Walter Roberson
Walter Roberson 2020년 12월 10일
subs(s_fs(fs), {A,B,C}, {newA, newB, newC} )
is what you need sometimes, if the replacements are non-scalar

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

답변 (1개)

Walter Roberson
Walter Roberson 2020년 12월 8일
This is expected behavior.
a = 2
b = a*5 + 1
a = 3
What value do you expect b to have now? Do you expect b to remember the formula used for its creation and update its value as the variables involved change? Or do you expect that b will use the current values of the variables as of the time b was assigned to and to not update when the variables change?
sym a
b = a*5 + 1
a = 2
What value does b have now? Do you expect (etc)?
When you do
syms a
then a in the MATLAB workspace gets assigned a definite value, with that value being "reference to a variable that lives in the symbolic engine". When you use that a to construct b, the value "reference to a variable that lives in the symbolic engine" is what gets copied, not the name of the matlab variable. So if the matlab variable changes, b does not change and still refers to the symbolic engine variable.
Your mistake was in using @ with an expression that involved symbolic variables. You should use matlabFunction instead, and make sure that you use the 'vars' option. This will give something like
f(x, A, B)
and you then pass in numeric values for A and B
  댓글 수: 1
Walter Roberson
Walter Roberson 2020년 12월 11일
subs(s_fs(fs), A, 5:8)
for example. s_fs is not anonymous function as you discussed before, it is symbolic function

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

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by