Solve a system of linear equations Ax = B for x in C#
6 views (last 30 days)
Show older comments
I want to solve a system of linear equations Ax = B for x.
Currently I'm doing this in MATLAB using "A\B", but I'm struggling a lot to implement this in C#.
My A is a 72x24 double. My B is a 72x1 double.
I tried the following:
var A = MathNet.Numerics.LinearAlgebra.CreateMatrix.DenseOfArray(Array A);
var b = MathNet.Numerics.LinearAlgebra.CreateVector.DenseOfArray(Array B);
var x = A.Solve(b);
I get the error "System.ArgumentException: 'Matrix dimensions must agree'"
Sample with smaller arrays but with specific values:
var A = MathNet.Numerics.LinearAlgebra.CreateMatrix.DenseOfArray(new double[,] { { 115, 82, 68, 13225, 6724, 4624, 641240, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 115, 82, 68, 13225, 6724, 4624, 641240, 1, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115, 82, 68, 13225, 6724, 4624, 641240, 1 } });
var b = MathNet.Numerics.LinearAlgebra.CreateMatrix.DenseOfArray(new double[,] { { 37.986 }, { 13.555 }, { 14.059 } });
var x = A.Solve(b);
I did a lot of research and still haven't found anything that works.
Any help will be very appreciated!
Thanks!
0 Comments
Answers (1)
Albert
on 22 Feb 2023
Edited: Albert
on 22 Feb 2023
I test your code and have the same exception. I guess it's because you have more variables to solve than equations you provide.
In your example code, dimension of A is
, and dimension of b is
, which means you have 3 equations, while you have 24 variables to solve, which will cause `Solve` method to complain.
I don't know the solution to this problem (how to solve the precise value of proper value of x), but if you just want to let the code run without exception, copy the existing equations to enlarge the A to
(meanwhile enlarge b as well) will work.
See this link which describes exactly the same problem: solve an underdetermined linear equations system in c#
0 Comments
See Also
Categories
Find more on Systems of Nonlinear Equations 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!