1

[1] C#: Solving a system of equations using Math.NET library

// test solver in Math.NET
var A = Matrix<double>.Build.DenseOfArray(new double[,] {
                                {1, 1, 3},
                                {2, 0, 4},
                                {-1, 6, -1}
                            });
Console.WriteLine(A);
var b = Vector<double>.Build.Dense(new double[] { 2, 19, 8 });
Console.WriteLine(b);
var x = A.Solve(b);//Math.NET

Console.WriteLine("Test Solver in Math.NET: " + x);
>> Test Solver in Math.NET: DenseVector 3-Double
 34.5
    5
-12.5

Press any key to continue . . .

[2] Results for the same inputs in MATLAB:

A = [1 1 3; 2 0 4; -1 6 -1]
B = [2 19 8]
x = B/A
A =

     1     1     3
     2     0     4
    -1     6    -1


B =

     2    19     8


x =

   1.0000e+00   2.0000e+00   3.0000e+00

[3] In Python for the same input and with the help of numpy.linalg:

In[10]: 
import numpy as np

# matrix A
A = np.matrix ([[1, 1, 3],[2, 0, 4],[-1, 6, -1]])

# vector b
b = np.array([2, 19, 8])
b.shape = (3,1)
# attempt to solve Ax=b
z = np.linalg.solve(A,b)
z
Out[10]: 
array([[ 34.5],
       [  5. ],
       [-12.5]])

[4] The results seem to be same for C#(Math.NET) and Python where as for MATLAB it is largely different, why is this so ?

opto abhi
  • 317
  • 1
  • 3
  • 13

1 Answers1

1

The C# and Python examples solve the equation A*x=b, while the MATLAB example solves x*A=b.

The MATLAB example can be changed to solve A*x=b by transposing B and using \ instead of /.

The Math.NET (and Python) examples can be changed to solve x*A=b by transposing A, i.e. A.Transpose().Solve(b) instead of A.Solve(b).

Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34