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 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0
What just happened?
The message returned in Command 1 tells us that Octave interprets the variable as a sparse matrix with 5 rows and 6 columns. The nnz
variable indicates the number of...