How to separate negative and positive terms in to two different expressions

I am using symolic vavriables
syms a b c d f g
Where all syms variables are positive
and have, for example the following expression A
F=a- b*d+ g*c-a*c+ d*g
my actual expression is much longer but how can I separate the negative vs the positive terms and put them in say in x and y?
I appreciate any help .
Thank you!

 Accepted Answer

Try this
syms a b c d f g
F = a - b*d + g*c - a*c + d*g;
parts = children(F);
parts = [parts{:}];
assume(symvar(parts)>0)
sgns = sign(parts);
assume(symvar(parts), 'clear')
x = parts(sgns==1);
y = parts(sgns==-1);

4 Comments

Thanks Ameer it gives me error saying :
Error using sym/subsref
Too many output arguments.
Error in (line 6)
parts = [parts{:}];
Which MATLAB release are you using? You may be able create a cell array
syms a b c d f g
F = a - b*d + g*c - a*c + d*g;
parts = children(F);
assume([a b c d f g]>0)
sgns = cellfun(@sign, parts);
assume([a b c d f g], 'clear')
x = parts(sgns==1);
y = parts(sgns==-1);
gives this:
Error using cellfun
Input #2 expected to be a cell array, was sym instead.
Error in negativepositive (line 17)
sgns = cellfun(@sign, parts);
it is 2012a . But thanks anyways Ameer :) I will be going for an upgrade, it is way old I guess.
Yes, it seems something related to old release. It seems that children() does not return a cell array in your case.

Sign in to comment.

More Answers (0)

Asked:

on 3 Dec 2020

Commented:

on 3 Dec 2020

Community Treasure Hunt

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

Start Hunting!