Solve a system of linear equations Ax = B for x in C#
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Albert
am 22 Feb. 2023
Bearbeitet: Albert
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Systems of Nonlinear Equations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!