如果只是简单的矩阵运算,不想调用第三方库,可以自己实现矩阵运算,直接上代码:
public class Matrix
{
private double[,] matrix;
/// <summary>
/// 初始化矩阵
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public Matrix(int x, int y)
{
this.matrix = new double[x, y];
this.Width = x;
this.Height = y;
}
/// <summary>
/// 矩阵索引器
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public double this[int x, int y]
{
get { return this.matrix[x, y]; }
set { this.matrix[x, y] = value; }
}
/// <summary>
/// 获取列
/// </summary>
/// <param name="c">列索引</param>
/// <returns></returns>
public double[] GetColumn(int c)
{
double[] column = new double[this.Width];
for (int i = 0; i < this.Width; i++)
{
column[i] = this.matrix[i, c];
}
return column;
}
/// <summary>
/// 获取行
/// </summary>
/// <param name="r">行索引</param>
/// <returns></returns>
public double[] GetRow(int r)
{
double[] row = new double[this.Height];
for (int i = 0; i < this.Height; i++)
{
row[i] = this.matrix[r, i];
}
return row;
}
/// <summary>
/// 宽
/// </summary>
public int Width { get; private set; }
/// <summary>
/// 高
/// </summary>
public int Height { get; private set; }
public static Matrix operator +(Matrix m1, Matrix m2)
{
Matrix m = new Matrix(m1.Width, m1.Height);
for (int i = 0; i < m.Width; i++)
{
for (int j = 0; j < m.Height; j++)
{
m[i, j] = m1[i, j] + m2[i, j];
}
}
return m;
}
public static Matrix operator -(Matrix m1, Matrix m2)
{
Matrix m = new Matrix(m1.Width, m1.Height);
for (int i = 0; i < m.Width; i++)
{
for (int j = 0; j < m.Height; j++)
{
m[i, j] = m1[i, j] - m2[i, j];
}
}
return m;
}
public static Matrix operator *(Matrix m1, Matrix m2)
{
Matrix m = new Matrix(m1.Width, m1.Height);
for (int i = 0; i < m.Width; i++)
{
for (int j = 0; j < m.Height; j++)
{
m[i, j] = m1[i, j] * m2[i, j];
}
}
return m;
}
public static Matrix operator /(Matrix m1, Matrix m2)
{
Matrix m = new Matrix(m1.Width, m1.Height);
for (int i = 0; i < m.Width; i++)
{
for (int j = 0; j < m.Height; j++)
{
m[i, j] = m1[i, j] / m2[i, j];
}
}
return m;
}
}
以上代码已经实现了运算符重载,如 Matrix =Matrix1+Matrix2 ;