Search code examples
matlabsparse-matrix

Extract the Compressed Column Storage vectors from MATLAB sparse matrix


I have the following matrix in MATLAB.

A =

     1     3     0     2     0
     0     1     0     0     2
     0     0     4     0     0
     1     0     0     0     4
     0     2     0     2     0

I can get the triplet form from using the sparse(A) command but is there a built in way to get the column_pointer, row_index and the values from MATLAB or should I write the code? (I have a working code in C++ to convert from triplet to Compressed Column Storage which I have to port over to a .m file, I presume)

MATLAB's find() still gives triplet form. But I want the compressed column storage form as shown below. (MATLAB is 1 index based. So the i think both col_ptr and row_index might be incremented by 1)

col_ptr =   [0 2 5 6 8 10];
row_index = [ 0 3 0 1 4 2 0 4 1 3]
values  =   [ 1 1 3 1 2 4 2 2 2 4]

Solution

  • I think this does it:

    col_ptr = [0 cumsum(sum(A~=0,1))];
    [row_index, ~, values] = find(A);
    row_index = row_index.'-1;
    values = values.';