2016-03-07 364 views
1

我想在矩陣Compressed Column Storage中乘以矩陣和向量。該矩陣是:矩陣向量乘法CCS C++

0 3 0 
4 0 0 
2 0 0 

這裏是CCS形式:

[ 4 2 3 ] 
[ 2 3 1 ] 
[ 1 3 4 4 ] 

的載體是:

[ 1 3 4 ] 

所以產品應該是

[ 9 4 2 ] 

這裏是函數我正在嘗試創建

vector<int> multiply(vector<int> val,vector<int> col,vector<int> row,vector<int> v, int r){ 

    vector<int> x(v.size()); 
    for (int j=0; j<r; j++) { 
     for (int i=col[j]-1; i<col[j+1]-1; i++) { 
      cout<<"\n"<<val[i]<<"*"<<v[j]<<"\n"; 
      x[j]+= val[i]*v[j]; 
     } 
    } 
    return x; 
} 

但這返回

[ 6 9 0 ] 

這是我已經得到了真正的解決方案最接近的,我怎麼能解決這個問題?

+0

首先,在調試器中逐行執行代碼。如果這樣做沒有幫助,那麼您可以嘗試創建一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve),包括向我們展示如何初始化傳遞給函數和實際調用?還包括您*整個*程序的預期和實際輸出。 –

+0

我在終端中運行程序,所以我不知道如何使用調試器 – user906357

+0

如果您在Linux(或使用Cygwin或MinGW的Windows)上,請使用[GDB](https://www.gnu。 org/software/gdb /),你是在OSX上,然後使用[LLDB](http://lldb.llvm.org/)。這些是IDE使用的實際調試器,它們也可以在命令行模式下使用。學習如何使用調試器,命令行或集成到IDE中,對開發人員非常重要。調試程序很困難,特別是嵌套循環或遞歸,但編程不容易,調試是一項關鍵技能。 –

回答

1

我想這是由col_ptr向量驅動的。

1.)我不確定可以使用什麼樣的值,所以我刪除了它,因爲我們不需要這些信息來解決問題 2.)我應該注意到我沒有編譯過這個,但我相信算法是正確的 3.)有一些明顯的方法來優化這段代碼的內存使用情況,但我留下了這些變量來幫助解釋這個過程。 4.)你發佈的代碼的主要問題是,它似乎沒有使用行數組來告訴我們該值在哪一行!

vector<int> multiply(vector<int> val,vector<int> col,vector<int> row,vector<int> v) { 
    vector<int> x(v.size()); 
    //we may need to initialize x as all zeroes, I forget 
    int col_size = col.size(); 
    int column_idx = 0; 
    for (int j=0; j<col_size-1; j++) { 
     //j indicates where the columns start going! 
     //columns end prior to the next column start 
     //val_index is where we need to start in the val array, for this column 
     int val_index_start = col[j]-1; //this is redunda 
     //we keep traversing forward until the next column starts 
     int next_column_start = col[j+1]-1; 
     for (int k=val_index_start; k < next_column_start && k < v.size(); k++) { 
     int row_of_cell = row[k] - 1; 
     int column_of_cell = column_idx; 
     int product = v[column_idx]*val[k]; 
     x[row_of_cell] += product; 
     } 
     column_idx++; 
    } 
    return x; 
}