How do I get subs to behave as desired for symbolic expressions ... does collect change an expression?

1 回表示 (過去 30 日間)
I am trying to simplify a large symbolic expression and am running into a problem.
The problem is represented by the following code:
syms a b x
f = a*x + b*x + a*b*x*x
subs(f,a+b,'c')
subs(collect(f,x),a+b,'c')
Here, I see two different behaviors from subs. In the first, the substitution of a+b with c is ignored and the original expression is returned. In the second, the desired behavior occurs and the resulting expression replaces a*x+b*x with c*x. Is there something I am missing -- how can I get the first subs to work?
In a related issue, I am finding that the follwing code yields baffling results:
isequal(f,f)
isequal(f,collect(f,x))
The first equality check returns true -- as expected since f should equal itself. However, the second equality check returns false. Is this expected behavior, and if so, how does someone check for equality between expressions?

採用された回答

Walter Roberson
Walter Roberson 2019 年 8 月 17 日
collect(f,x) is a different expression with a different internal symbol than f is.
isAlways(f==collect(f,x))
It is tempting to use
simplify(f-collect(f,x))
but in sufficiently complicated expressions, simplify() will not be able to prove that the value is 0. For example, if you rewrite complex values into exp and sincos, then the transform is too advanced for simplify() to detect equality.
  3 件のコメント
Brandon Laflen
Brandon Laflen 2019 年 8 月 22 日
Thanks Walter, these are useful tips. Especially, using subs(f,a,c-b) makes it work as desired when I follow with a simplify.
Do you happen to know if isAlways(f==collect(f,x)) is guaranteed to always return true, regardless of f?
Walter Roberson
Walter Roberson 2019 年 8 月 22 日
No, there is a known case where it will fail: f = sym(nan) then isAlways will return false because NaN == NaN is considered to be false.
I do not know if there are expressions that are too complicated for isAlways to prove.
You should watch out for the cases that isAlways cannot prove; see https://www.mathworks.com/help/symbolic/isalways.html

サインインしてコメントする。

その他の回答 (0 件)

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by