5
syms Gr Ra Ri A B Gr1 Gr2 c d
Gr =  2*c*(Ra^2 - Ri^2) - d*(Ra^4 - Ri^4)/2;
Gr1 = subs(Gr, [c*(Ra^2 - Ri^2), -d*(Ra^4 - Ri^4)/2], [A, B])
Gr2 = subs(Gr, [c*(Ra^2 - Ri^2),  d*(Ra^4 - Ri^4)/2], [A, B])

returns

Gr1 =

2*A + B


Gr2 =

2*A - (d*(Ra^4 - Ri^4))/2

Is there a way to convince MATLAB to return Gr2 = 2*A - B in the second case without workarounds? I have a much more complex expression to substitute, but I can't work with this subs()-behaviour. Thanks.

Thomas
  • 67
  • 7
  • 1
    Is this solution okay for you? `Gr2 = subs(Gr, [c*(Ra^2 - Ri^2), -d*(Ra^4 - Ri^4)/2], [A, -B])` – Nemesis Apr 09 '15 at 08:26
  • Unfortunately not. I need something without a workaround, because the the expression I want to substitute has something like B and -B in it. Do I really have to use subs() with B and -B? I don't understand why this is not done by Matlab automatically. – Thomas Apr 09 '15 at 08:33
  • I tested it on Octave and i did not get such beahviour – articuno Apr 09 '15 at 11:02
  • 1
    Something as simple as `syms A B;` `subs(-2*A,2*A,B)` fails in R2015a. It doesn't matter if I `assume` the variables are real or positive. Unfortunately, MuPAD's `subs` and `subsex` exhibit identical behavior. Your only solution may be to convert the symbolic expressions to character strings and use something like [`strrep`](http://mathworks.com/help/matlab/ref/strrep.html) to replace exact sub-strings (you could try `regexprep` too to match multiple cases). I'd report this to The MathWorks by [filing a service request](http://www.mathworks.com/company/aboutus/contact_us/?s_tid=gn_cntus). – horchler Apr 21 '15 at 15:10

2 Answers2

1

I think the problem is in the multiplication/division operations in the second argument of subs since the problem vanishes once I rearrange the code as follows:

syms Gr Ra Ri A B Gr1 Gr2 c d
Gr =  2*c*(Ra^2 - Ri^2) - d*(Ra^4 - Ri^4)/2;
Gr1 = subs(Gr, [(Ra^2 - Ri^2),(Ra^4 - Ri^4)], [A/c,-2*B/d])
Gr2 = subs(Gr, [(Ra^2 - Ri^2),(Ra^4 - Ri^4)], [A/c,2*B/d])

and the output is:

Gr1 =
2*A + B

Gr2 =  
2*A - B
brainkz
  • 1,335
  • 10
  • 16
  • Interesting... As suggested by @horchler, I'll report this dubious MATLAB behaviour to MathWorks. – Thomas Apr 27 '15 at 07:03
0

The described behaviour was classified by the Matlab development team as unexpected and will hopefully be fixed in future releases:

http://www.mathworks.com/matlabcentral/answers/213727-subs-unexpected-simplification-behaviour#answer_177179

Thomas
  • 67
  • 7