Search code examples
matlabsparse-matrix

Constructing Sparse Matrices,what does sparse do?


let us consider following matrix

 A = [ 0   0   0   5
      0   2   0   0
      1   3   0   0
      0   0   4   0]

A =

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

if we do

sparse(A)

ans =

   (3,1)        1
   (2,2)        2
   (3,2)        3
   (4,3)        4
   (1,4)        5

it shows just nonzero elements and indexes also of these elements,but how can i use this data to construct new vector or array?also i wanted to understand following command

S = sparse(i,j,s,m,n) 

it's definition says that

i and j are vectors of row and column indices, respectively, for the nonzero elements of the matrix. s is a vector of nonzero values whose indices are specified by the corresponding (i,j) pairs. m is the row dimension for the resulting matrix, and n is the column dimension.

but does it help us to create new array or generally what is idea of sparse command?i know it is optimization of storage and taking only nonzero elements,but how can we use result in further calculation?thanks in advance


Solution

  • This is just storage issue, use the sparse matrix as a normal one:

    A = [ 0   0   0   5
          0   2   0   0
          1   3   0   0
          0   0   4   0];
    
    B = [ 1   6   1   5
          6   2   0   0
          9   3   5   9
          8   7   4   0];
    
    
    A = sparse(A); % Reduce memory footprint
    
    C = B*A; % Continue thinking of matrix A as a normal matrix
    
    D = A(:, 2); % Address elements as if A is normal matrix ...
                 % i.e. D = [0 2 3 0].'
    

    The syntax:

    S = sparse(i,j,s,m,n);
    

    is for constructing the matrix as sparse one directly (no temporary allocation of a normal one):

    n = 4; % Final row count
    m = 4; % Final column count
    i = [3 2 3 4 1]; % Non null rows indices
    j = [1 2 2 3 4]; % Non null columns indices
    s = [1 2 3 4 5]; % Non null values    
    AA = sparse(i, j, s, n, m) % Same matrix as 'sparse(A)' without temporary allocation of full A