2009-02-23 90 views
2

我想在C#中使用一些簡單的循環來添加兩個矩陣。我將結果存儲在數據網格視圖中。但是,最後一個單元格似乎沒有添加。我一直在看這個代碼一段時間,似乎無法弄清楚。我做錯什麼了嗎?在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]; 
      } 
     } 
    } 

回答

2

你肯定你的矩陣具有完全相同的尺寸,論文兩行很奇怪,因爲反正你從一個矩陣的行數,但來自另一列數。

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

我相信你的錯誤是,MSDN狀態Item屬性(用於與[]運營商類似數組的訪問)是:

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

但你永諾用它按倒序排列(列之前的行)。

+0

對不起,我打算解決這個問題,當矩陣相乘時你如何確定矩陣的大小 – Kredns 2009-02-23 00:45:33

+0

另外,請記住當.AllowUserToAddRows == true – 2009-02-23 00:56:34

1

在像C#這樣的語言中,你並不需要擔心這個東西。有經過測試的類庫可以爲你做這類事情,重要的是,它們可以利用處理器的SIMD指令等進行優化。如果語言有運算符重載,那麼你只需要聲明你的矩陣作爲對象,並將它們與簡單的結果= mat_a + mat_b一起添加。