欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

c# 矩阵运算加、减、乘 - 掘金

最编程 2024-05-22 11:51:23
...

您好,以下是C#中矩阵运算的加减乘实现方法:

  1. 矩阵加法

矩阵加法的规则是两个矩阵对应位置的元素相加。具体实现方法如下:

public static double[,] Add(double[,] a, double[,] b)
{
    int rows = a.GetLength(0);
    int cols = a.GetLength(1);
    double[,] result = new double[rows, cols];

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            result[i, j] = a[i, j] + b[i, j];
        }
    }

    return result;
}
  1. 矩阵减法

矩阵减法的规则是两个矩阵对应位置的元素相减。具体实现方法如下:

public static double[,] Subtract(double[,] a, double[,] b)
{
    int rows = a.GetLength(0);
    int cols = a.GetLength(1);
    double[,] result = new double[rows, cols];

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            result[i, j] = a[i, j] - b[i, j];
        }
    }

    return result;
}
  1. 矩阵乘法

矩阵乘法的规则是矩阵A的行与矩阵B的列一一对应相乘再求和。具体实现方法如下:

public static double[,] Multiply(double[,] a, double[,] b)
{
    int aRows = a.GetLength(0);
    int aCols = a.GetLength(1);
    int bRows = b.GetLength(0);
    int bCols = b.GetLength(1);

    if (aCols != bRows)
    {
        throw new Exception("矩阵A的列数必须等于矩阵B的行数");
    }

    double[,] result = new double[aRows, bCols];

    for (int i = 0; i < aRows; i++)
    {
        for (int j = 0; j < bCols; j++)
        {
            double sum = 0;

            for (int k = 0; k < aCols; k++)
            {
                sum += a[i, k] * b[k, j];
            }

            result[i, j] = sum;
        }
    }

    return result;
}

希望以上代码能够帮助您实现C#中的矩阵加减乘运算。如果您有其他问题,可以随时提出。