【问题标题】:Adding Matrices in C#?在 C# 中添加矩阵?
【发布时间】:2009-02-23 00:33:38
【问题描述】:

我正在尝试使用一些简单的 for 循环在 C# 中将两个矩阵相加。我将结果存储在数据网格视图中。但是,最后一个单元格似乎没有添加。我一直在看这段代码一段时间,似乎无法弄清楚。我是不是做错了什么?

    // Adds two matrices together using arrays.
    private void menuItemAdd_Click(object sender, EventArgs e)
    {
        // Create two 2-D arrays
        int[,] matrixOne = new int[dgvMatrixOne.RowCount, dgvMatrixOne.ColumnCount];
        int[,] matrixTwo = new int[dgvMatrixTwo.RowCount, dgvMatrixTwo.ColumnCount];

        // The rows of the total matrix match the rows of the first matrix.
        dgvMatrixTotal.RowCount = dgvMatrixOne.RowCount;

        // The columns of the total matrix match the columns of the first matrix.
        dgvMatrixTotal.ColumnCount = dgvMatrixOne.ColumnCount;

        // Fill matrix one with the data in the data grid matrix one.
        for (int i = 0; i < dgvMatrixOne.RowCount; i++)
        {
            for (int j = 0; j < dgvMatrixOne.ColumnCount; j++)
            {
                matrixOne[i, j] = Convert.ToInt32(dgvMatrixOne[i, j].Value);
            }
        }

        // Fill matrix two with the data in the data grid matrix two.
        for (int i = 0; i < dgvMatrixTwo.RowCount; i++)
        {
            for (int j = 0; j < dgvMatrixTwo.ColumnCount; j++)
            {
                matrixTwo[i, j] = Convert.ToInt32(dgvMatrixTwo[i, j].Value);
            }
        }

        // Set the total data grid to matrix one + matrix two.
        for (int i = 0; i < dgvMatrixOne.RowCount; i++)
        {
            for (int j = 0; j < dgvMatrixOne.ColumnCount; j++)
            {
                dgvMatrixTotal[i, j].Value = matrixOne[i, j] + matrixTwo[i, j];
            }
        }
    }

【问题讨论】:

    标签: c# arrays matrix


    【解决方案1】:

    你确定你的矩阵有完全相同的大小吗,这两行很奇怪,因为你从一个矩阵中获取行数,但从另一个矩阵中获取列数。

    dgvMatrixTotal.RowCount = dgvMatrixOne.RowCount;
    dgvMatrixTotal.ColumnCount = dgvMatrixTwo.ColumnCount;
    

    我相信您的错误是 MSDN 声明 Item 属性(用于使用 [] 运算符进行类似数组的访问)是:

    public DataGridViewCell this [
        int columnIndex,
        int rowIndex
    ] { get; set; }
    

    但你总是按倒序使用它(行在列之前)。

    【讨论】:

    • 抱歉,我要修正一下,原来这就是矩阵相乘时确定矩阵大小的方式
    • 另外,请记住,当 .AllowUserToAddRows == true 时,.RowCount 将减一
    • 我已经将它设置为 false,因为它会自动添加行并造成相当大的困境。
    【解决方案2】:

    在像 C# 这样的语言中,您无需担心这些问题。有经过试验和测试的类库可以为您做这种事情,重要的是,它们已经过优化,可以利用处理器的 SIMD 指令等。如果语言有运算符重载,您只需要声明您的矩阵作为对象,并将它们与简单的结果相加 = mat_a + mat_b。

    【讨论】:

    • 很抱歉没有在问题中指定这一点,但我正在尝试重新发明轮子以了解有关轮子的更多信息。我知道那里有免费的图书馆,但我认为这将是一个很好的爱好项目。
    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    相关资源
    最近更新 更多