Creation - Untitled
Description: Untitled

Next: Information, Previous: Storage, Up: Basics

#### 20.1.2 Creating Sparse Matrices

There are several means to create sparse matrix.

Returned from a function
  There are many functions that directly return sparse matrices. These include speye, sprand, spdiag, etc.
Constructed from matrices or vectors
  The function sparse allows a sparse matrix to be constructed from three vectors representing the row, column and data. Alternatively, the function spconvert uses a three column matrix format to allow easy importation of data from elsewhere.
Created and then filled
  The function sparse or spalloc can be used to create an empty matrix that is then filled by the user
From a user binary program
  The user can directly create the sparse matrix within an oct-file.

There are several basic functions to return specific sparse matrices. For example the sparse identity matrix, is a matrix that is often needed. It therefore has its own function to create it as `speye (`n`)` or `speye (`r`,` c`)`, which creates an n-by-n or r-by-c sparse identity matrix.

Another typical sparse matrix that is often needed is a random distribution of random elements. The functions sprand and sprandn perform this for uniform and normal random distributions of elements. They have exactly the same calling convention, where `sprand (`r`,` c`,` d`)`, creates an r-by-c sparse matrix with a density of filled elements of d.

Other functions of interest that directly create sparse matrices, are spdiag or its generalization spdiags, that can take the definition of the diagonals of the matrix and create the sparse matrix that corresponds to this. For example

         s = spdiag (sparse(randn(1,n)), -1);

creates a sparse (n+1)-by-(n+1) sparse matrix with a single diagonal defined.

— Loadable Function: spatan2 (y, x)

> Compute atan (Y / X) for corresponding sparse matrix elements of Y and X. The result is in range -pi to pi.

— Loadable Function: y = spcumprod (x,dim)

> Cumulative product of elements along dimension dim. If dim is omitted, it defaults to 1 (column-wise cumulative products).

> See also: spcumsum.

— Loadable Function: y = spcumsum (x,dim)

> Cumulative sum of elements along dimension dim. If dim is omitted, it defaults to 1 (column-wise cumulative sums).

> See also: spcumprod.

— Loadable Function: spdiag (v, k)

> Return a diagonal matrix with the sparse vector v on diagonal k. The second argument is optional. If it is positive, the vector is placed on the k-th super-diagonal. If it is negative, it is placed on the -k-th sub-diagonal. The default value of k is 0, and the vector is placed on the main diagonal. For example,

>               spdiag ([1, 2, 3], 1)
>               ans =

>               Compressed Column Sparse (rows=4, cols=4, nnz=3)
>                 (1 , 2) -> 1
>                 (2 , 3) -> 2
>                 (3 , 4) -> 3

> Given a matrix argument, instead of a vector, `spdiag` extracts the k-th diagonal of the sparse matrix.

> See also: diag.

— Function File: [b, c] = spdiags (a)
— Function File: b = spdiags (a, c)
— Function File: b = spdiags (v, c, a)
— Function File: b = spdiags (v, c, m, n)

> A generalization of the function `spdiag`. Called with a single input argument, the non-zero diagonals c of A are extracted. With two arguments the diagonals to extract are given by the vector c.

> The other two forms of `spdiags` modify the input matrix by replacing the diagonals. They use the columns of v to replace the columns represented by the vector c. If the sparse matrix a is defined then the diagonals of this matrix are replaced. Otherwise a matrix of m by n is created with the diagonals given by v.

> Negative values of c represent diagonals below the main diagonal, and positive values of c diagonals above the main diagonal.

> For example

>               spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4)
>               =>    5 10  0  0
>                     1  6 11  0
>                     0  2  7 12
>                     0  0  3  8
>                     0  0  0  4

— Function File: y = speye (m)
— Function File: y = speye (m, n)
— Function File: y = speye (sz)

> Returns a sparse identity matrix. This is significantly more efficient than `sparse (eye (`m`))` as the full matrix is not constructed.

> Called with a single argument a square matrix of size m by m is created. Otherwise a matrix of m by n is created. If called with a single vector argument, this argument is taken to be the size of the matrix to create.

— Function File: y = spfun (f,x)

> Compute `f(`x`)` for the non-zero values of x. This results in a sparse matrix with the same structure as x. The function f can be passed as a string, a function handle or an inline function.

— Mapping Function: spmax (x, y, dim)
— Mapping Function: [w, iw] = spmax (x)

> For a vector argument, return the maximum value. For a matrix argument, return the maximum value from each column, as a row vector, or over the dimension dim if defined. For two matrices (or a matrix and scalar), return the pair-wise maximum. Thus,

>               max (max (x))

> returns the largest element of x, and

>               max (2:5, pi)
>                   =>  3.1416  3.1416  4.0000  5.0000

> compares each element of the range `2:5` with `pi`, and returns a row vector of the maximum values.

> For complex arguments, the magnitude of the elements are used for comparison.

> If called with one input and two output arguments, `max` also returns the first index of the maximum value(s). Thus,

>               [x, ix] = max ([1, 3, 5, 2, 5])
>                   =>  x = 5
>                       ix = 3

— Mapping Function: spmin (x, y, dim)
— Mapping Function: [w, iw] = spmin (x)

> For a vector argument, return the minimum value. For a matrix argument, return the minimum value from each column, as a row vector, or over the dimension dim if defined. For two matrices (or a matrix and scalar), return the pair-wise minimum. Thus,

>               min (min (x))

> returns the smallest element of x, and

>               min (2:5, pi)
>                   =>  2.0000  3.0000  3.1416  3.1416

> compares each element of the range `2:5` with `pi`, and returns a row vector of the minimum values.

> For complex arguments, the magnitude of the elements are used for comparison.

> If called with one input and two output arguments, `min` also returns the first index of the minimum value(s). Thus,

>               [x, ix] = min ([1, 3, 0, 2, 5])
>                   =>  x = 0
>                       ix = 3

— Function File: y = spones (x)

> Replace the non-zero entries of x with ones. This creates a sparse matrix with the same structure as x.

— Loadable Function: y = spprod (x,dim)

> Product of elements along dimension dim. If dim is omitted, it defaults to 1 (column-wise products).

> See also: spsum, spsumsq.

— Function File: sprand (m, n, d)
— Function File: sprand (s)

> Generate a random sparse matrix. The size of the matrix will be m by n, with a density of values given by d. d should be between 0 and 1. Values will be uniformly distributed between 0 and 1.

> Note: sometimes the actual density may be a bit smaller than d. This is unlikely to happen for large really sparse matrices.

> If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero.

> See also: sprandn.

— Function File: sprandn (m, n, d)
— Function File: sprandn (s)

> Generate a random sparse matrix. The size of the matrix will be m by n, with a density of values given by d. d should be between 0 and 1. Values will be normally distributed with mean of zero and variance 1.

> Note: sometimes the actual density may be a bit smaller than d. This is unlikely to happen for large really sparse matrices.

> If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero.

> See also: sprand.

— Function File: sprandsym (n, d)
— Function File: sprandsym (s)

> Generate a symmetric random sparse matrix. The size of the matrix will be n by n, with a density of values given by d. d should be between 0 and 1. Values will be normally distributed with mean of zero and variance 1.

> Note: sometimes the actual density may be a bit smaller than d. This is unlikely to happen for large really sparse matrices.

> If called with a single matrix argument, a random sparse matrix is generated wherever the matrix S is non-zero in its lower triangular part.

> See also: sprand, sprandn.

— Loadable Function: y = spsum (x,dim)

> Sum of elements along dimension dim. If dim is omitted, it defaults to 1 (column-wise sum).

> See also: spprod, spsumsq.

— Loadable Function: y = spsumsq (x,dim)

> Sum of squares of elements along dimension dim. If dim is omitted, it defaults to 1 (column-wise sum of squares). This function is equivalent to computing

>               spsum (x .* spconj (x), dim)

> but it uses less memory and avoids calling `spconj` if x is real.

> See also: spprod, spsum.

The recommended way for the user to create a sparse matrix, is to create two vectors containing the row and column index of the data and a third vector of the same size containing the data to be stored. For example

           ri = ci = d = [];
           for j = 1:c
             ri = [ri; randperm(r)(1:n)'];
             ci = [ci; j*ones(n,1)];
             d = [d; rand(n,1)];
           endfor
           s = sparse (ri, ci, d, r, c);

creates an r-by-c sparse matrix with a random distribution of n (<r) elements per column. The elements of the vectors do not need to be sorted in any particular order as Octave will sort them prior to storing the data. However, pre-sorting the data will make the creation of the sparse matrix faster.

The function spconvert takes a three or four column real matrix. The first two columns represent the row and column index respectively and the third and four columns, the real and imaginary parts of the sparse matrix. The matrix can contain zero elements and the elements can be sorted in any order. Adding zero elements is a convenient way to define the size of the sparse matrix. For example

         s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]')
         => Compressed Column Sparse (rows=4, cols=4, nnz=3)
               (1 , 1) -> 1
               (2 , 3) -> 2
               (3 , 4) -> 3

An example of creating and filling a matrix might be

         k = 5;
         nz = r * k;
         s = spalloc (r, c, nz)
         for j = 1:c
           idx = randperm (r);
           s (:, j) = [zeros(r - k, 1); ...
                 rand(k, 1)] (idx);
         endfor

It should be noted, that due to the way that the Octave assignment functions are written that the assignment will reallocate the memory used by the sparse matrix at each iteration of the above loop. Therefore the spalloc function ignores the nz argument and does not preassign the memory for the matrix. Therefore, it is vitally important that code using to above structure should be vectorized as much as possible to minimize the number of assignments and reduce the number of memory allocations.

— Loadable Function: FM = full (SM)

> returns a full storage matrix from a sparse one

> See also: sparse.

— Function File: s = spalloc (r, c, nz)

> Returns an empty sparse matrix of size r-by-c. As Octave resizes sparse matrices at the first opportunity, so that no additional space is needed, the argument nz is ignored. This function is provided only for compatibility reasons.

> It should be noted that this means that code like

>               k = 5;
>               nz = r * k;
>               s = spalloc (r, c, nz)
>               for j = 1:c
>                 idx = randperm (r);
>                 s (:, j) = [zeros(r - k, 1); rand(k, 1)] (idx);
>               endfor

> will reallocate memory at each step. It is therefore vitally important that code like this is vectorized as much as possible.

> See also: sparse, nzmax.

— Loadable Function: s = sparse (a)

> Create a sparse matrix from the full matrix a. is forced back to a full matrix is resulting matrix is sparse — Loadable Function: s = sparse (i, j, sv, m, n, nzmax)

> > Create a sparse matrix given integer index vectors i and j, a 1-by-`nnz` vector of real of complex values sv, overall dimensions m and n of the sparse matrix. The argument `nzmax` is ignored but accepted for compatibility with Matlab.

> > Note: if multiple values are specified with the same i, j indices, the corresponding values in s will be added.

> > The following are all equivalent:

> >               s = sparse (i, j, s, m, n)
> >               s = sparse (i, j, s, m, n, "summation")
> >               s = sparse (i, j, s, m, n, "sum")

> > — Loadable Function: s = sparse (i, j, s, m, n, "unique")

> > > Same as above, except that if more than two values are specified for the same i, j indices, the last specified value will be used. — Loadable Function: s = sparse (i, j, sv)

> > > > Uses m`= max (`i`)`, n`= max (`j`)` — Loadable Function: s = sparse (m, n)

> > > > > Equivalent to `sparse ([], [], [],` m`,` n`, 0)`

> > > > > If any of sv, i or j are scalars, they are expanded to have a common size.

> > > > > See also: full.

— Function File: x = spconvert (m)

> This function converts for a simple sparse matrix format easily produced by other programs into Octave's internal sparse format. The input x is either a 3 or 4 column real matrix, containing the row, column, real and imaginary parts of the elements of the sparse matrix. An element with a zero real and imaginary part can be used to force a particular matrix size.

— Loadable Function: spfind (x)
— Loadable Function: spfind (x, n)
— Loadable Function: spfind (x, n, direction)
— Loadable Function: [i, j, v spfind (...)

> A sparse version of the `find` function. Please see the `find` for details of its use.

> Note that this function is particularly useful for sparse matrices, as it extracts the non-zero elements as vectors, which can then be used to create the original matrix. For example,

>               sz = size(a);
>               [i, j, v] = spfind (a);
>               b = sparse(i, j, v, sz(1), sz(2));

> See also: sparse.

The above problem can be avoided in oct-files. However, the construction of a sparse matrix from an oct-file is more complex than can be discussed in this brief introduction, and you are referred to chapter Dynamically Linked Functions, to have a full description of the techniques involved.