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

1 次查看(过去 30 天)
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.

请先登录,再进行评论。

回答(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

类别

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