math-suite/Source/MatrixCalculator/Helpers/MatrixConverter.cs

52 lines
1.4 KiB
C#
Raw Permalink Normal View History

2018-02-05 23:24:46 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using MathNet.Numerics.LinearAlgebra;
namespace MatrixCalculator
{
static class MatrixConverter
{
/// <summary>
/// Puts a matrix in a DataTable
/// </summary>
public static DataTable GetTable(Matrix<double> matrix)
{
DataTable table = new DataTable("matrix");
for (int i = 0; i < matrix.ColumnCount; i++)
table.Columns.Add();
for (int i = 0; i < matrix.RowCount; i++)
{
table.Rows.Add("");
for (int j = 0; j < matrix.ColumnCount; j++)
table.Rows[i][j] = matrix[i, j].ToString();
}
return table;
}
/// <summary>
/// Converts a DataTable into a matrix
/// </summary>
public static Matrix<double> FromTable(DataTable table)
{
Matrix<double> matrix = Matrix<double>.Build.Dense(table.Rows.Count, table.Columns.Count);
for (int i = 0; i < matrix.RowCount; i++)
for (int j = 0; j < matrix.ColumnCount; j++)
{
double temp = 0;
double.TryParse(table.Rows[i][j].ToString(), out temp);
matrix[i, j] = temp;
}
return matrix;
}
}
}