<html lang="en"> <head> <title>Creating Sparse Matrices - GNU Octave</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Octave"> <meta name="generator" content="makeinfo 4.13"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="Basics.html#Basics" title="Basics"> <link rel="prev" href="Storage-of-Sparse-Matrices.html#Storage-of-Sparse-Matrices" title="Storage of Sparse Matrices"> <link rel="next" href="Information.html#Information" title="Information"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family:serif; font-weight:normal; } span.sansserif { font-family:sans-serif; font-weight:normal; } --></style> </head> <body> <div class="node"> <a name="Creating-Sparse-Matrices"></a> <p> Next: <a rel="next" accesskey="n" href="Information.html#Information">Information</a>, Previous: <a rel="previous" accesskey="p" href="Storage-of-Sparse-Matrices.html#Storage-of-Sparse-Matrices">Storage of Sparse Matrices</a>, Up: <a rel="up" accesskey="u" href="Basics.html#Basics">Basics</a> <hr> </div> <h4 class="subsection">22.1.2 Creating Sparse Matrices</h4> <p>There are several means to create sparse matrix. <dl> <dt>Returned from a function<dd>There are many functions that directly return sparse matrices. These include <dfn>speye</dfn>, <dfn>sprand</dfn>, <dfn>diag</dfn>, etc. <br><dt>Constructed from matrices or vectors<dd>The function <dfn>sparse</dfn> allows a sparse matrix to be constructed from three vectors representing the row, column and data. Alternatively, the function <dfn>spconvert</dfn> uses a three column matrix format to allow easy importation of data from elsewhere. <br><dt>Created and then filled<dd>The function <dfn>sparse</dfn> or <dfn>spalloc</dfn> can be used to create an empty matrix that is then filled by the user <br><dt>From a user binary program<dd>The user can directly create the sparse matrix within an oct-file. </dl> <p>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 <code>speye (</code><var>n</var><code>)</code> or <code>speye (</code><var>r</var><code>, </code><var>c</var><code>)</code>, which creates an <var>n</var>-by-<var>n</var> or <var>r</var>-by-<var>c</var> sparse identity matrix. <p>Another typical sparse matrix that is often needed is a random distribution of random elements. The functions <dfn>sprand</dfn> and <dfn>sprandn</dfn> perform this for uniform and normal random distributions of elements. They have exactly the same calling convention, where <code>sprand (</code><var>r</var><code>, </code><var>c</var><code>, </code><var>d</var><code>)</code>, creates an <var>r</var>-by-<var>c</var> sparse matrix with a density of filled elements of <var>d</var>. <p>Other functions of interest that directly create sparse matrices, are <dfn>diag</dfn> or its generalization <dfn>spdiags</dfn>, that can take the definition of the diagonals of the matrix and create the sparse matrix that corresponds to this. For example, <pre class="example"> s = diag (sparse(randn(1,n)), -1); </pre> <p class="noindent">creates a sparse (<var>n</var>+1)-by-(<var>n</var>+1) sparse matrix with a single diagonal defined. <!-- spdiags scripts/sparse/spdiags.m --> <p><a name="doc_002dspdiags"></a> <div class="defun"> — Function File: [<var>b</var>, <var>c</var>] = <b>spdiags</b> (<var>A</var>)<var><a name="index-spdiags-2176"></a></var><br> — Function File: <var>b</var> = <b>spdiags</b> (<var>A, c</var>)<var><a name="index-spdiags-2177"></a></var><br> — Function File: <var>b</var> = <b>spdiags</b> (<var>v, c, A</var>)<var><a name="index-spdiags-2178"></a></var><br> — Function File: <var>b</var> = <b>spdiags</b> (<var>v, c, m, n</var>)<var><a name="index-spdiags-2179"></a></var><br> <blockquote><p>A generalization of the function <code>diag</code>. Called with a single input argument, the non-zero diagonals <var>c</var> of <var>A</var> are extracted. With two arguments the diagonals to extract are given by the vector <var>c</var>. <p>The other two forms of <code>spdiags</code> modify the input matrix by replacing the diagonals. They use the columns of <var>v</var> to replace the columns represented by the vector <var>c</var>. If the sparse matrix <var>A</var> is defined then the diagonals of this matrix are replaced. Otherwise a matrix of <var>m</var> by <var>n</var> is created with the diagonals given by <var>v</var>. <p>Negative values of <var>c</var> represent diagonals below the main diagonal, and positive values of <var>c</var> diagonals above the main diagonal. <p>For example: <pre class="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 </pre> </blockquote></div> <!-- speye scripts/sparse/speye.m --> <p><a name="doc_002dspeye"></a> <div class="defun"> — Function File: <var>y</var> = <b>speye</b> (<var>m</var>)<var><a name="index-speye-2180"></a></var><br> — Function File: <var>y</var> = <b>speye</b> (<var>m, n</var>)<var><a name="index-speye-2181"></a></var><br> — Function File: <var>y</var> = <b>speye</b> (<var>sz</var>)<var><a name="index-speye-2182"></a></var><br> <blockquote><p>Return a sparse identity matrix. This is significantly more efficient than <code>sparse (eye (</code><var>m</var><code>))</code> as the full matrix is not constructed. <p>Called with a single argument a square matrix of size <var>m</var> by <var>m</var> is created. Otherwise a matrix of <var>m</var> by <var>n</var> is created. If called with a single vector argument, this argument is taken to be the size of the matrix to create. </p></blockquote></div> <!-- spones scripts/sparse/spones.m --> <p><a name="doc_002dspones"></a> <div class="defun"> — Function File: <var>r</var> = <b>spones</b> (<var>S</var>)<var><a name="index-spones-2183"></a></var><br> <blockquote><p>Replace the non-zero entries of <var>S</var> with ones. This creates a sparse matrix with the same structure as <var>S</var>. </p></blockquote></div> <!-- sprand scripts/sparse/sprand.m --> <p><a name="doc_002dsprand"></a> <div class="defun"> — Function File: <b>sprand</b> (<var>m, n, d</var>)<var><a name="index-sprand-2184"></a></var><br> — Function File: <b>sprand</b> (<var>s</var>)<var><a name="index-sprand-2185"></a></var><br> <blockquote><p>Generate a random sparse matrix. The size of the matrix will be <var>m</var> by <var>n</var>, with a density of values given by <var>d</var>. <var>d</var> should be between 0 and 1. Values will be uniformly distributed between 0 and 1. <p>If called with a single matrix argument, a random sparse matrix is generated wherever the matrix <var>S</var> is non-zero. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dsprandn.html#doc_002dsprandn">sprandn</a>, <a href="doc_002dsprandsym.html#doc_002dsprandsym">sprandsym</a>. </p></blockquote></div> <!-- sprandn scripts/sparse/sprandn.m --> <p><a name="doc_002dsprandn"></a> <div class="defun"> — Function File: <b>sprandn</b> (<var>m, n, d</var>)<var><a name="index-sprandn-2186"></a></var><br> — Function File: <b>sprandn</b> (<var>s</var>)<var><a name="index-sprandn-2187"></a></var><br> <blockquote><p>Generate a random sparse matrix. The size of the matrix will be <var>m</var> by <var>n</var>, with a density of values given by <var>d</var>. <var>d</var> should be between 0 and 1. Values will be normally distributed with mean of zero and variance 1. <p>If called with a single matrix argument, a random sparse matrix is generated wherever the matrix <var>S</var> is non-zero. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dsprand.html#doc_002dsprand">sprand</a>, <a href="doc_002dsprandsym.html#doc_002dsprandsym">sprandsym</a>. </p></blockquote></div> <!-- sprandsym scripts/sparse/sprandsym.m --> <p><a name="doc_002dsprandsym"></a> <div class="defun"> — Function File: <b>sprandsym</b> (<var>n, d</var>)<var><a name="index-sprandsym-2188"></a></var><br> — Function File: <b>sprandsym</b> (<var>s</var>)<var><a name="index-sprandsym-2189"></a></var><br> <blockquote><p>Generate a symmetric random sparse matrix. The size of the matrix will be <var>n</var> by <var>n</var>, with a density of values given by <var>d</var>. <var>d</var> should be between 0 and 1. Values will be normally distributed with mean of zero and variance 1. <p>If called with a single matrix argument, a random sparse matrix is generated wherever the matrix <var>S</var> is non-zero in its lower triangular part. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dsprand.html#doc_002dsprand">sprand</a>, <a href="doc_002dsprandn.html#doc_002dsprandn">sprandn</a>. </p></blockquote></div> <p>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, <pre class="example"> ri = ci = d = []; for j = 1:c ri = [ri; randperm(r,n)']; ci = [ci; j*ones(n,1)]; d = [d; rand(n,1)]; endfor s = sparse (ri, ci, d, r, c); </pre> <p class="noindent">creates an <var>r</var>-by-<var>c</var> sparse matrix with a random distribution of <var>n</var> (<<var>r</var>) 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. <p>The function <dfn>spconvert</dfn> 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: <pre class="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 </pre> <p>An example of creating and filling a matrix might be <pre class="example"> 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 </pre> <p>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 <dfn>spalloc</dfn> function ignores the <var>nz</var> argument and does not pre-assign 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. <!-- full src/data.cc --> <p><a name="doc_002dfull"></a> <div class="defun"> — Loadable Function: <var>FM</var> = <b>full</b> (<var>SM</var>)<var><a name="index-full-2190"></a></var><br> <blockquote><p>Return a full storage matrix from a sparse, diagonal, permutation matrix or a range. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dsparse.html#doc_002dsparse">sparse</a>. </p></blockquote></div> <!-- spalloc src/sparse.cc --> <p><a name="doc_002dspalloc"></a> <div class="defun"> — Loadable Function: <var>s</var> = <b>spalloc</b> (<var>m, n, nz</var>)<var><a name="index-spalloc-2191"></a></var><br> <blockquote><p>Create an <var>m</var>-by-<var>n</var> sparse matrix with pre-allocated space for at most <var>nz</var> nonzero elements. This is useful for building the matrix incrementally by a sequence of indexed assignments. Subsequent indexed assignments will reuse the pre-allocated memory, provided they are of one of the simple forms <ul> <li><var>s</var><code>(I:J) = </code><var>x</var> <li><var>s</var><code>(:,I:J) = </code><var>x</var> <li><var>s</var><code>(K:L,I:J) = </code><var>x</var> </ul> <p><b>and</b> that the following conditions are met: <ul> <li>the assignment does not decrease nnz(<var>S</var>). <li>after the assignment, nnz(<var>S</var>) does not exceed <var>nz</var>. <li>no index is out of bounds. </ul> <p>Partial movement of data may still occur, but in general the assignment will be more memory and time-efficient under these circumstances. In particular, it is possible to efficiently build a pre-allocated sparse matrix from contiguous block of columns. <p>The amount of pre-allocated memory for a given matrix may be queried using the function <code>nzmax</code>. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dnzmax.html#doc_002dnzmax">nzmax</a>, <a href="doc_002dsparse.html#doc_002dsparse">sparse</a>. </p></blockquote></div> <!-- sparse src/sparse.cc --> <p><a name="doc_002dsparse"></a> <div class="defun"> — Loadable Function: <var>s</var> = <b>sparse</b> (<var>a</var>)<var><a name="index-sparse-2192"></a></var><br> — Loadable Function: <var>s</var> = <b>sparse</b> (<var>i, j, sv, m, n, nzmax</var>)<var><a name="index-sparse-2193"></a></var><br> — Loadable Function: <var>s</var> = <b>sparse</b> (<var>i, j, sv</var>)<var><a name="index-sparse-2194"></a></var><br> — Loadable Function: <var>s</var> = <b>sparse</b> (<var>i, j, s, m, n, "unique"</var>)<var><a name="index-sparse-2195"></a></var><br> — Loadable Function: <var>s</var> = <b>sparse</b> (<var>m, n</var>)<var><a name="index-sparse-2196"></a></var><br> <blockquote><p>Create a sparse matrix from the full matrix or row, column, value triplets. If <var>a</var> is a full matrix, convert it to a sparse matrix representation, removing all zero values in the process. <p>Given the integer index vectors <var>i</var> and <var>j</var>, a 1-by-<code>nnz</code> vector of real of complex values <var>sv</var>, overall dimensions <var>m</var> and <var>n</var> of the sparse matrix. The argument <code>nzmax</code> is ignored but accepted for compatibility with <span class="sc">matlab</span>. If <var>m</var> or <var>n</var> are not specified their values are derived from the maximum index in the vectors <var>i</var> and <var>j</var> as given by <var>m</var><code> = max (</code><var>i</var><code>)</code>, <var>n</var><code> = max (</code><var>j</var><code>)</code>. <p><strong>Note</strong>: if multiple values are specified with the same <var>i</var>, <var>j</var> indices, the corresponding values in <var>s</var> will be added. <p>The following are all equivalent: <pre class="example"> s = sparse (i, j, s, m, n) s = sparse (i, j, s, m, n, "summation") s = sparse (i, j, s, m, n, "sum") </pre> <p>Given the option "unique". if more than two values are specified for the same <var>i</var>, <var>j</var> indices, the last specified value will be used. <p><code>sparse(</code><var>m</var><code>, </code><var>n</var><code>)</code> is equivalent to <code>sparse ([], [], [], </code><var>m</var><code>, </code><var>n</var><code>, 0)</code> <p>If any of <var>sv</var>, <var>i</var> or <var>j</var> are scalars, they are expanded to have a common size. <!-- Texinfo @sp should work but in practice produces ugly results for HTML. --> <!-- A simple blank line produces the correct behavior. --> <!-- @sp 1 --> <p class="noindent"><strong>See also:</strong> <a href="doc_002dfull.html#doc_002dfull">full</a>. </p></blockquote></div> <!-- spconvert scripts/sparse/spconvert.m --> <p><a name="doc_002dspconvert"></a> <div class="defun"> — Function File: <var>x</var> = <b>spconvert</b> (<var>m</var>)<var><a name="index-spconvert-2197"></a></var><br> <blockquote><p>This function converts for a simple sparse matrix format easily produced by other programs into Octave's internal sparse format. The input <var>x</var> 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. </p></blockquote></div> <p>The above problem of memory reallocation can be avoided in oct-files. However, the construction of a sparse matrix from an oct-file is more complex than can be discussed here, and you are referred to chapter <a href="Dynamically-Linked-Functions.html#Dynamically-Linked-Functions">Dynamically Linked Functions</a>, to have a full description of the techniques involved. </body></html>