MATLAB: How to solve symbolic equations

symbolic

Hi,
I am new to matlab and I am trying to solve symbolic equations.
Here is my code:
syms h a b p1 p2 r1 r2 d1 d2
p1=1/(1+d1)
p2=1/(1+d2)
h=((a-b)*(p1*(r1-d1)-p2*(r2-d2))+1)/2
h1=diff(h,d1)
h2=diff(h,d2)
eqs=[-(-h/(1+d1)^2+h1*p1)*(r1-d1)-(a/(a+b)-h*p1)+h1*p2*(r2-d2)==0, (h2*p2+(1-h)/(1+d2)^2)*(r2-d2)-(a/(a-b)-p2*(1-h))-h2*p1*(r1-d1)==0]
unknowns=[p1,p2]
If I use solv=solve(eqs,unknowns) then it says The second argument must be a vector of symbolic variables.
What command should I use to solve for p1 and p2? And how can I put in a values for a, b and r1 to find the relationships between p1,p2 and r2?
Thank you very much.

Best Answer

syms h(d1,d2) a b p1 p2 r1 r2
P1 = 1/(1+d1);
P2 = 1/(1+d2);
h(d1, d2) = subs( ((a-b)*(p1*(r1-d1)-p2*(r2-d2))+1)/2, [p1 p2], [P1 P2]);
h1 = diff(h,d1);
h2 = diff(h,d2);
eqs = subs( [-(-h/(1+d1)^2+h1*p1)*(r1-d1)-(a/(a+b)-h*p1)+h1*p2*(r2-d2)==0, (h2*p2+(1-h)/(1+d2)^2)*(r2-d2)-(a/(a-b)-p2*(1-h))-h2*p1*(r1-d1)==0], [p1 p2], [P1 P2]);
D1 = solve(p1 == P1, d1);
D2 = solve(p2 == P2, d2);
eqns2 = subs( eqs, [d1 d2], [D1 D2]);
unknowns = [p1,p2];
sol = solve(eqns2, unknowns, 'ReturnConditions', true)
This will give 16 solutions, 8 of which are for the case that a is 0, and the other 8 for the case that a is not 0. 0 is the solution under several of the possibilities.
The solutions involve the roots of a degree 8 polynomial. The solver does not even attempt to merge the coefficients, so it comes out pretty long and unreadable (and the root expression occurs up to 5 times per solution of p1).
You can manually force MATLAB to take children of expressions until you extract the repeated root() term (using subexpr() helps some), after which you can strip the root() holder off using children(). Take that expression and apply coeffs() to it to pull out the various z terms. You can then simplify that. Multiply back by the powers of z (second output of coeffs) and sum to get a polynomial that is a bit easier to read. This basic polynomial has its roots extracted multiple times in the general solution for p1, but in different places different root numbers are used.
It might have been easier to solve your original equations for d1 and d2 and then to transform that to get p1 and p2. Or easier, perhaps, to use the p1 and p2 assignments as equations instead and then to solve for p1, p2, d1, d2... I did not try that.