2015-06-23 30 views
0

我已經編寫了一個程序,它給出兩個矩陣的隨機值,然後使用乘法打印出第三個矩陣。矩陣1是3x3(行,列),矩陣2是(3x2)。矩陣乘法w /隨機值錯誤輸出

我的輸出如下:

Matrix 1: 
    4 6 0 
    9 1 5 
    4 7 5 
Matrix 2: 
    4 6 
    0 9 
    1 5 
matrix 1 x matrix 2: 
16 78 97059710 
41 88 218384285 
21 112 97059715 

正如你可以看到第三矩陣給人以怪異值的額外的行/列。 (97057910等)

下面是我的多重功能,用C++編寫:

Matrix Matrix::multiply(Matrix one, Matrix two) { 

    int n1 = one.data[0].size(); 
    int n2 = two.data.size(); 

    int nCommon = one.data.size(); 

    vector< vector<int> > temp(nCommon); 

    for (int i = 0 ; i < nCommon ; i++) 
     temp[i].resize(n2); 

    for(int i=0;i<n1;i++) { 
     for(int j=0;j<n2;j++) { 
      for(int k=0;k<nCommon;k++) { 
       temp[i][j]= temp[i][j] + one.data[i][k] * two.data[k][j]; 
      } 
     } 
    } 

    const Matrix result = Matrix(temp); 
    return result; 
} 

有沒有人對如何解決這個問題的任何建議?我想刪除那些奇怪的值,只有兩列。

+0

'矢量< vector>溫度(nCommon );'似乎可疑,你的意思可能是'std :: vector > temp(n1,std :: vector (n2));' – Jarod42

+0

你的第一個問題可以追溯到你對矩陣乘法的理解。也許在別的之前查看它。 M [3x3] X N [3x2] = P [3x3]是無意義的。你可以有M [3x3] x N [3x2] = P [3x2]。 – Pandrei

回答

0

你得到你的行數和列數混在一起。我們的想法是乘以(1×K)的B(K X J)和下面的代碼做什麼:

int n1 = one.data[0].size(); // this is K 
int n2 = two.data.size(); // this is also K 

int nCommon = one.data.size(); // this is I 

vector< vector<int> > temp(nCommon); 

for (int i = 0 ; i < nCommon ; i++) 
    temp[i].resize(n2); 

// temp is now I x K, which is not what was intended, 
// and the iteration over rows and columns will not be correct. 

試試這個:

int n1 = one.data.size(); // this is I 
int n2 = two.data[0].size(); // this is J 

int nCommon = two.data.size(); // this is K 

vector< vector<int> > temp(n1); 
for (int i = 0 ; i < nCommon ; i++) 
    temp[i].resize(n2); 
+0

你真了不起。有效。謝謝一堆! – nick3h

0

即使您的某個矩陣只有兩列,看起來您的for-loop仍會嘗試訪問每行第三列中的值。從0

two.data[k][j] 

ķ迭代到one.data.size() -1,或0..2。

j也從0反覆到two.data.size() -1,也是0..2。

但是,根據您的描述,two的矩陣的第二維度範圍僅爲0..1。

未定義的行爲。代碼運行超過矢量的末尾,並讀取垃圾。