How can I solve a Matrix in MathNet?
-
21-03-2021 - |
質問
I can't figure out how to get the values for the resulting matrix using MathNet, can anyone please help? I have a 4 column, 3 row matrix which represents 3 polynomials and I am trying to solve for a=, b=, c=. row1 representing a, 2 b, 3 c. I cannot figure out how to use MathNet's functionality to get these values or if it even does that.
double X1 = Convert.ToDouble(x1);
double Y1 = Convert.ToDouble(y1);
double X2 = Convert.ToDouble(x2);
double Y2 = Convert.ToDouble(y2);
double X3 = Convert.ToDouble(x3);
double Y3 = Convert.ToDouble(y3);
var a = new DenseMatrix(3, 4);
double[] row1 = new double[2];
row1[0] = X1;
row1[1] = Y1;
double[] row2 = new double[2];
row2[0] = X2;
row2[1] = Y2;
double[] row3 = new double[2];
row3[0] = X3;
row3[1] = Y3;
a.SetRow(0, row1);
a.SetRow(1, row2);
a.SetRow(2, row3);
EDIT:
If you want to try the solution you can set matrix = to
double[,] matrix = new double[3, 4]{
{ 1, 2, -1, -4 },
{ 2, 3, -1, -11 },
{ -2, 0, -3, 22 }
};
解決
Solved not even using MathNet:
int lead = 0, rowCount = 3, columnCount = 4;
for (int r = 0; r < rowCount; r++)
{
if (columnCount <= lead) break;
int i = r;
while (matrix[i, lead] == 0)
{
i++;
if (i == rowCount)
{
i = r;
lead++;
if (columnCount == lead)
{
lead--;
break;
}
}
}
for (int j = 0; j < columnCount; j++)
{
double temp = matrix[r, j];
matrix[r, j] = matrix[i, j];
matrix[i, j] = temp;
}
double div = matrix[r, lead];
for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;
for (int j = 0; j < rowCount; j++)
{
if (j != r)
{
double sub = matrix[j, lead];
for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
}
}
lead++;
}
所属していません StackOverflow