Split components of a symbolic vector into positive and negative

5 views (last 30 days)
Given a symbolic expression I would like to split the positive and negative terms and further split if the coefficients are not 1. I would like to obtain a vector whose components are the positive terms and another vector whose components are the negative terms of the expression.
Let me illustrate with an example:
Variables x1 x2 y1 y2
Given X=x1^2*y2^5 - 2*y1^2*x1*x2+ 3*x1 -y2
I would like to obtain two vector Vp=[x1^2*y2, x1, x1, x1] (notice that x1 appears 3 times since the coefficient in front of x1 is 3) Vn=[y1^2*x1*x2, y1^2*x1*x2, y2] (notice that y1^2*x1*x2 appears 2 times since the coefficient in front of y1^2*x1*x2 is -2)
I do not care about the specific order of the elements in each vector.
I know how to separate positive and negative components but not split the coefficients further. I would obtain something like this instead:
Vp=[x1^2*y2, 3*x1] Vn=[2*y1^2*x1*x2, y2]

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 28 Jun 2015
syms x1 x2 y1 y2
X=x1^2*y2^5 - 2*y1^2*x1*x2+ 3*x1 -y2
[s1,s2]=coeffs(X,[x1,x2,y1,y2]);
idxp=s1>0;
Xp1=s2(idxp);
Xn1=s2(~idxp);
ip=s1(idxp);
in=s1(~idxp)
Vp=[];
Vn=[];
for k=1:numel(Xp1)
Vp=[Vp repmat(Xp1(k),1,ip(k))];
end
for k=1:numel(Xn1)
Vn=[Vn repmat(Xn1(k),1,abs(in(k)))];
end
Vp
Vn

Categories

Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!