轉載地址:http://blog.csdn.net/bigpiglet_zju/article/details/20791881
稀疏矩陣(Sparse Matrix)由於有很多0,爲了節省空間,一般壓縮存儲。通常只需要保存非零元素及其位置即可。
下面介紹Compressed Row Storage(CRS)格式或者稱爲 Compressed sparse row(CSR)格式,由名稱可見,該格式是把行的信息壓縮存儲了,只顯式保留每行第一個非零元素的位置,具體在例子中可以看到。
假設有稀疏矩陣A,我們需要創建三個數組,一個浮點型數組val,另外兩個爲整型數組(col_ind, row_ptr)。
val數組,大小爲矩陣A的非零元素的個數,保存矩陣A的非零元素(按從上往下,從左往右的行遍歷方式訪問元素)。
col_ind數組,和val數組一樣,大小爲矩陣A的非零元素的個數,保存val數組中元素的列索引。其數學表示爲:
row_ptr數組,大小爲矩陣A的行數,保存矩陣A的每行第一個非零元素在val中的索引。其數學表示爲:
按照慣例,一般定義row_ptr(n+1) = nnz + 1,而nnz是A中非零元素的個數。
該方法可以節省很多空間,只需要2nnz + n + 1個存儲單元,而不是n的平方個單元。
//ps:這的n好像指的是:方陣的行/列
看一個例子:
矩陣A定義爲
其CSR格式由三個數組定義爲:
注意其中row_ptr數組的最後一個元素爲20(19+1),因爲矩陣A的非零元素爲19。
Compressed Column Storage
Analogous to CRS, there is compressed column storage (CCS), which is also called the Harwell-Boeing sparse matrix format [139]. The CCS format is identical to the CRS format except that the columns of are stored (traversed) instead of the rows. In other words, the CCS format is the CRS format for .
The CCS format is specified by the arrays {val, row_ind, col_ptr}, where row_ind stores the row indices of each nonzero, and col_ptr stores the index of the elements in val which start a column of . The CCS format for the matrix in (10.1) is given by
val | 10 | 3 | 3 | 9 | 7 | 8 | 4 | 8 | 8 9 | 2 | 3 | 13 | -1 | ||
row_ind | 1 | 2 | 4 | 2 | 3 | 5 | 6 | 3 | 4 5 | 6 | 2 | 5 | 6 |
col_ptr | 1 | 4 | 8 | 10 | 13 | 17 | 20 |
參考:
1. Compressed Row Storage
http://web.eecs.utk.edu/~dongarra/etemplates/node373.html
2. Compressed Column Storage
http://www.netlib.org/utk/people/JackDongarra/etemplates/node374.html
3. Sparse Matrix Compression Formats
http://www.cs.colostate.edu/~mroberts/toolbox/c++/sparseMatrix/sparse_matrix_compression.html