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 个评论
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
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
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 Center 和 File Exchange 中查找有关 Symbolic Math Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!