Search code examples
pythonmatlabcomplex-numbers

Python and matlab gives different answers


I need to get 3 values from 3 equations as part of an error correcting method for S-parameters. The equations are shown below.

enter image description here

The matlab code went as follows.

syms a b c
eqn1 = (G_A1*a)+(b)-(G_A1*G_M1*c) == G_M1; %short
eqn2 = (G_A2*a)+(b)-(G_A2*G_M2*c) == G_M2; %load 
eqn3 = (G_A3*a)+(b)-(G_A3*G_M3*c) == G_M3; %open

%[A,B] = equationsToMatrix([eq1, eq2, eq3], [a, b, c]);
%res = linsolve(A,B);

sol = solve([eqn1, eqn2, eqn3], [a, b, c]);
aSol = sol.a;
bSol = sol.b;
cSol = sol.c;

Giving me the results:

4.9284 - 2.8505i

-11.1951 -37.7373i

-31.2705 -64.5481i

The code used in Python was

a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3*G_M3)]])
b = np.array([G_M1,G_M2,G_M3])
x = np.linalg.solve(a, b)

Giving

-0.24421332 -0.021397452j

-10.1681071 -37.679968ej

-0.77652264 -0.0377357202j

It the code used in Python incorrect?


Solution

  • You need to switch columns and rows in your a-matrix. Try the following change to your python code and you should get the same results as in matlab.

    a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3*G_M3)]])
    a = a.transpose()
    b = np.array([G_M1,G_M2,G_M3])
    x = np.linalg.solve(a, b)
    

    To understand this, consider your example, and take the first row of a*x.

    This would result in

    G_A1*x1+G_A2*x2+G_A3*x3 = G_M1

    Looking at your picture, what you want is a.transpose()*x.