Search code examples
matlabsymbolic-math

Algebraic simultaneous equations using symbolic toolbox in MATLAB


I am trying to use the symbolic toolbox of MATLAB to solve the following systems of equations. Given the following three equations

w+x+y+z==k1;
(w^2)+(x^2)+(y^2)+(z^2)==k2;
w*x*y*z==k3;

where k1, k2, and k3 are constants and w, x, y, and z are variables. The objective is to obtain p and q in terms of each other only where

p==w+z;
q==(w*z)-(x*y); 

That is, w, x, y, z should get eliminated in the p and q equations to get a single function, f(p,q,k1,k2,k3).

I am using the code in the following manner:

syms w x y z p q
eqn1 = w+x+y+z==k1;
eqn2 = w*x*y*z==k2;
eqn3 = (w^2)+(x^2)+(y^2)+(z^2)==k3;
eqn4 = w+z-p==0;
eqn5 = (w*z)-(x*y)-q==0;
solve(eqn1,eqn2,eqn3,eqn4,eqn5)

but the output is for w, x, etc. instead of one equation (in terms of variables p and q and the constants k1, k2, and k3). How to achieve this single function equation?


Solution

  • I am going to extract a function, that will get p and give q.

    assuming that we have (k1,k2,k3,p) and then we want q.

    So equations are:

    [k1,k2,k3,p]=f(w,x,y,z);

    We want to inverse the f function. Meaning that we have [k1,k2,k3,p] and we want [x,y,z,w](4 equation and 4 unknown variable). Then we can calculate q by using [x,y,z,w].

    use the following code. Remember that there is not a single answer. Equation has 2 answer.

        clc
        clear all
    
        syms w x y z p q k1 k2 k3
        eqn1 = w+x+y+z-k1;
        eqn2 = w*x*y*z-k2;
        eqn3 = (w^2)+(x^2)+(y^2)+(z^2)-k3;
        eqn4 = w+z-p;
    
        s=solve(eqn1,eqn2,eqn3,eqn4);
        x=s.x;
        y=s.y;
        z=s.z;
        w=s.w;
    
        q=(w.*z)-(x.*y); 
    
        %Removing repeated answers
        i=1;
        while i<=length(q)
            v=(simplify(q(i)-q)==0)&(1:length(q)~=i).';
            if any(v)
                q(v)=[];
                i=1;
            else
                i=i+1;
            end
        end
        %Displaying unique answers
        for i=1:length(q)
            fprintf('Answer %d\nq=%s\n\n',i,char(q(i)));
        end