Solve a system of linear equations Ax = B for x in C#

6 ビュー (過去 30 日間)
Ruben Ferreira
Ruben Ferreira 2020 年 2 月 3 日
編集済み: Albert 2023 年 2 月 22 日
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!

回答 (1 件)

Albert
Albert 2023 年 2 月 22 日
編集済み: Albert 2023 年 2 月 22 日
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#

カテゴリ

Help Center および File ExchangeSystems of Nonlinear Equations についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by