Selecting positive or negative terms of a symbolic vector

I have a symbolic vector say [a^2*b^3, 0, -a*b^2, b^2, -a^4*b]. I would like to obtain two vectors from this. One of them only selecting the entries that have a positive coefficient, in this case I would like to obtain [a^2*b^3, b^2]. The other containing the entries with negative coefficient: [-a*b^2, -a^4*b].
I tried extracting the coefficients and then using if statement to create a vector with the positive entries and similar for the negative.
Is there a more efficient way to do this?

 Accepted Answer

This works:
syms a b c
V = [a^2*b^3, 0, -a*b^2, b^2, -a^4*b];
Vs = sign(V);
Vgz = V(Vs>0)
Vlz = V(Vs<0)
Vgz =
[ a^2*b^3, b^2]
Vlz =
[ -a*b^2, -a^4*b]

4 Comments

Thanks for your answer. However, I get this message:
Error using symengine (line 58) Unable to prove '0 < sign(a^2*b^3)' literally. To test the statement mathematically, use isAlways.
Error in sym/subsindex (line 659) X = find(mupadmex('symobj::logical',A.s,9)) - 1;
Error in sym>privformat (line 1473) x = subsindex(x)+1;
Error in sym/subsref (line 685) [inds{k},refs{k}] = privformat(inds{k});
Interesting. It worked for me without error in R2015a.
I can’t reproduce the behaviour you saw, so experiment with adding an assume call:
syms a b c
assume([a b c] > 0)
V = [a^2*b^3, 0, -a*b^2, b^2, -a^4*b];
Vs = sign(V);
Vgz = V(Vs>0)
Vlz = V(Vs<0)
It didn’t change the result I got, but it might be necessary for your version.
My pleasure!
(Please Accept my Answer if it solved your problem.)

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!