Time for action – instantiating a sparse matrix

  1. In Octave, we can define a matrix to be sparse using the sparse function. The simplest way to instantiate a sparse matrix with, say 5 rows and 6 columns, is:
    octave:1 > A=sparse(5,6)
    
    A=
    
     Compressed Column Sparse (rows=5, cols=6, nnz=0, [0%])
    
  2. To assign non-zero values to elements in the matrix, you simply use normal assignments, for example:
    octave:2> A(1,2) = 42; A(3,:)=3;
    
    octave:3> A
    
    A =
    
     Compressed Column Sparse (rows=5, cols=6, nnz=7, [23%])
    
       (3,1) ->1
    
       (1,2) -> 42
    
       (3,2) -> 1
    
       (3,3) -> 1
    
       (3,4) -> 1
    
       (3,5) -> 1
    
       (3,6) -> 1
    
  3. It is possible to extract the full matrix (and include all the zeros) from sparse matrix by using the full function:
    octave:4> B=full(A)
    
    B =
    
       0   42    0    0    0    0
    
       0    0    0    0    0    0
    
     3 3 ...

Get GNU Octave now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.