C#矩陣相乘
第一種:交叉陣列形式
-
/// <summary>
-
/// 矩陣乘法
-
/// <param name="matrix1">矩陣1</param>
-
/// <param name="matrix2">矩陣2</param>
-
/// <returns>積</returns>
-
private static double[][] MatrixMult(double[][] matrix1, double[][] matrix2)
-
{
-
//matrix1是m*n矩陣,matrix2是n*p矩陣,則result是m*p矩陣
-
int m = matrix1.Length, n = matrix2.Length, p = matrix2[0].Length;
-
double[][] result = new double[m][];
-
for (int i = 0; i < result.Length; i++)
-
{
-
result[i] = new double[p];
-
}
-
//矩陣乘法:c[i,j]=Sigma(k=1→n,a[i,k]*b[k,j])
-
for (int i = 0; i < m; i++)
-
{
-
for (int j = 0; j < p; j++)
-
{
-
//對乘加法則
-
for (int k = 0; k < n; k++)
-
{
-
result[i][j] += (matrix1[i][k] * matrix2[k][j]);
-
}
-
}
-
}
-
return result;
-
}
-
-
/// <summary>
-
/// 列印矩陣
-
/// </summary>
-
/// <param name="matrix">待列印矩陣</param>
-
private static void PrintMatrix(double[][] matrix)
-
{
-
for (int i = 0; i < matrix.Length; i++)
-
{
-
for (int j = 0; j < matrix[i].Length; j++)
-
{
-
Console.Write(matrix[i][j] + "\t");
-
}
-
Console.WriteLine();
-
}
第二種:二維陣列形式
-
/// <summary>
-
/// 矩陣乘法
-
/// <param name="matrix1">矩陣1</param>
-
/// <param name="matrix2">矩陣2</param>
-
/// <returns>積</returns>
-
private static double[,] MatrixMult(double[,] matrix1, double[,] matrix2)
-
{
-
//matrix1是m*n矩陣,matrix2是n*p矩陣,則result是m*p矩陣
-
int m = matrix1.GetLength(0), n = matrix2.GetLength(0), p = matrix2.GetLength(1);
-
double[,] result = new double[m,p];
-
//矩陣乘法:c[i,j]=Sigma(k=1→n,a[i,k]*b[k,j])
-
for (int i = 0; i < m; i++)
-
{
-
for (int j = 0; j < p; j++)
-
{
-
//對乘加法則
-
for (int k = 0; k < n; k++)
-
{
-
result[i,j] += (matrix1[i,k] * matrix2[k,j]);
-
}
-
}
-
}
-
return result;
-
}
-
-
/// <summary>
-
/// 列印矩陣
-
/// </summary>
-
/// <param name="matrix">待列印矩陣</param>
-
private static void PrintMatrix(double[,] matrix)
-
{
-
for (int i = 0; i < matrix.GetLength(0); i++)
-
{
-
for (int j = 0; j < matrix.GetLength(1); j++)
-
{
-
Console.Write(matrix[i,j] + "\t");
-
}
-
Console.WriteLine();
-
}