2015-08-03 215 views
1

我得到了以下問題:我得到了一個9x9矩陣,我想要將其減少到5x5矩陣。我想通過取消最後3行和列以及取消第3行和第3列來達到此目的。 我的代碼看起來像這樣。但它不能正常工作。C++減少矩陣的尺寸

for (int A=0;A<6;A++) 
    for (int B=0;B<6;B++) 
     if ((A!=2) || (B!=2)) 
      disshess5x5(A,B) = disshessian(A,B); 
+0

什麼不正常?它怎麼不工作? – Snappawapa

+0

我從這個[0.0887628得到,-0.0612372,0.122474,0,0,0,0,0,0, -0.0612372,0.0887628,0.122474,0,0,0,0,0,0, 0.122474,0.122474, -0.094949,0,0,0,0,0,0,0 ,0,0,0.15,0,0,0,0,0, 0,0,0,0,0.15,0,0,0 ,0, 0,0,0,0,0,0.15,0,0,0, 0,0,0,0,0,0,0.15,0,0, 0,0,0,0, 0,0,0,0.15,0, 0,0,0,0,0,0,0,0,0.15] – cag

+0

該矩陣[0.0887628,0,0,0,0, -0.0612372,0.0887628,0.122474 ,0,0, 0.122474,0.122474,0,0,0,0 ,0,0,0.15,0, 0,0,0,0,0.15 – cag

回答

0

它始終是明智的,在你試圖實現什麼明確的,所以它應該是易於閱讀。

在這個例子中,你應該定義要跳過的行和列:

const bool rowToSkip[9] = { false, false, true, false, false, false, true, true, true, true }; 
const bool colToSkip[9] {...}; 

前面已經回答了,你也應該定義源到目標的指數映射:

const int tgtRow[9] = {0,1,2,-1,3,4}; // and in the same way tgtCol 

有了這樣consts你會得到乾淨的循環,容易發現任何錯誤:

for(int i = 0; i < 9; ++i) 
if(!rowToSkip[i]) 
    for (int j = 0; j < 9; ++j) 
     if(!colToSkip[j]) 
     tgtMatrix[tgtRow[i]][tgtCol[j]] = srcMatrix[i][j]; 

[更新]

它可以在一個小更快的方式通過只是定義靶>源指標也做:

const int srcRow[5] = {0,1,3,4,5}; 
const int srcCol[5] = {0,1,3,4,5}; 

for(int i = 0; i < 5; ++i) 
    for (int j = 0; j < 5; ++j) 
     tgtMatrix[i][j] = srcMatrix[srcRow[i]][srcCol[j]]; 

順便說一句 - 你的範圍[0,6)length == 6 - 你應該使用[0,5)範圍,以滿足5x5矩陣

+0

這工作!但我將srcRow [5]更改爲{0,1,3,4,5}(與列相同),以便跳過第三個元素 – cag

+0

@cag更正,謝謝。 – PiotrNycz

0

您需要調整的跳躍行和col

for (int A=0;A<6;A++) 
    for (int B=0;B<6;B++) 
     if ((A!=2) && (B!=2)) 
      disshess5x5(A-(A>2),B-(B>2)) = disshessian(A,B); 

例如當A4要寫信給指數3來代替,而此代碼索引,因爲A>2true和意志做數學隱時被轉換爲1false代替轉換爲0,從而留下索引01不變)。