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

1 view (last 30 days)
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 Comments
Benjamin
Benjamin on 10 Dec 2020
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 on 10 Dec 2020
subs(s_fs(fs), {A,B,C}, {newA, newB, newC} )
is what you need sometimes, if the replacements are non-scalar

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 8 Dec 2020
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

Categories

Find more on Symbolic Math Toolbox 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!