1. 程式人生 > >C#矩陣相乘

C#矩陣相乘

第一種:交叉陣列形式
  1. /// <summary>

  2. /// 矩陣乘法

  3. /// <param name="matrix1">矩陣1</param>

  4. /// <param name="matrix2">矩陣2</param>

  5. /// <returns>積</returns>

  6. private static double[][] MatrixMult(double[][] matrix1, double[][] matrix2)

  7. {

  8. //matrix1是m*n矩陣,matrix2是n*p矩陣,則result是m*p矩陣

  9. int m = matrix1.Length, n = matrix2.Length, p = matrix2[0].Length;

  10. double[][] result = new double[m][];

  11. for (int i = 0; i < result.Length; i++)

  12. {

  13. result[i] = new double[p];

  14. }

  15. //矩陣乘法:c[i,j]=Sigma(k=1→n,a[i,k]*b[k,j])

  16. for (int i = 0; i < m; i++)

  17. {

  18. for (int j = 0; j < p; j++)

  19. {

  20. //對乘加法則

  21. for (int k = 0; k < n; k++)

  22. {

  23. result[i][j] += (matrix1[i][k] * matrix2[k][j]);

  24. }

  25. }

  26. }

  27. return result;

  28. }

  29.  

  30. /// <summary>

  31. /// 列印矩陣

  32. /// </summary>

  33. /// <param name="matrix">待列印矩陣</param>

  34. private static void PrintMatrix(double[][] matrix)

  35. {

  36. for (int i = 0; i < matrix.Length; i++)

  37. {

  38. for (int j = 0; j < matrix[i].Length; j++)

  39. {

  40. Console.Write(matrix[i][j] + "\t");

  41. }

  42. Console.WriteLine();

  43. }

第二種:二維陣列形式

  1. /// <summary>

  2. /// 矩陣乘法

  3. /// <param name="matrix1">矩陣1</param>

  4. /// <param name="matrix2">矩陣2</param>

  5. /// <returns>積</returns>

  6. private static double[,] MatrixMult(double[,] matrix1, double[,] matrix2)

  7. {

  8. //matrix1是m*n矩陣,matrix2是n*p矩陣,則result是m*p矩陣

  9. int m = matrix1.GetLength(0), n = matrix2.GetLength(0), p = matrix2.GetLength(1);

  10. double[,] result = new double[m,p];

  11. //矩陣乘法:c[i,j]=Sigma(k=1→n,a[i,k]*b[k,j])

  12. for (int i = 0; i < m; i++)

  13. {

  14. for (int j = 0; j < p; j++)

  15. {

  16. //對乘加法則

  17. for (int k = 0; k < n; k++)

  18. {

  19. result[i,j] += (matrix1[i,k] * matrix2[k,j]);

  20. }

  21. }

  22. }

  23. return result;

  24. }

  25.  

  26. /// <summary>

  27. /// 列印矩陣

  28. /// </summary>

  29. /// <param name="matrix">待列印矩陣</param>

  30. private static void PrintMatrix(double[,] matrix)

  31. {

  32. for (int i = 0; i < matrix.GetLength(0); i++)

  33. {

  34. for (int j = 0; j < matrix.GetLength(1); j++)

  35. {

  36. Console.Write(matrix[i,j] + "\t");

  37. }

  38. Console.WriteLine();

  39. }