<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by GNU Texinfo 6.5, http://www.gnu.org/software/texinfo/ --> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Creating Sparse Matrices (GNU Octave (version 5.1.0))</title> <meta name="description" content="Creating Sparse Matrices (GNU Octave (version 5.1.0))"> <meta name="keywords" content="Creating Sparse Matrices (GNU Octave (version 5.1.0))"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="Basics.html#Basics" rel="up" title="Basics"> <link href="Information.html#Information" rel="next" title="Information"> <link href="Storage-of-Sparse-Matrices.html#Storage-of-Sparse-Matrices" rel="prev" title="Storage of Sparse Matrices"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.indentedblock {margin-right: 0em} blockquote.smallindentedblock {margin-right: 0em; font-size: smaller} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} kbd {font-style: oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nolinebreak {white-space: nowrap} span.roman {font-family: initial; font-weight: normal} span.sansserif {font-family: sans-serif; font-weight: normal} ul.no-bullet {list-style: none} --> </style> <link rel="stylesheet" type="text/css" href="octave.css"> </head> <body lang="en"> <a name="Creating-Sparse-Matrices"></a> <div class="header"> <p> Next: <a href="Information.html#Information" accesskey="n" rel="next">Information</a>, Previous: <a href="Storage-of-Sparse-Matrices.html#Storage-of-Sparse-Matrices" accesskey="p" rel="prev">Storage of Sparse Matrices</a>, Up: <a href="Basics.html#Basics" accesskey="u" rel="up">Basics</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="Creating-Sparse-Matrices-1"></a> <h4 class="subsection">22.1.2 Creating Sparse Matrices</h4> <p>There are several means to create sparse matrix. </p> <dl compact="compact"> <dt>Returned from a function</dt> <dd><p>There are many functions that directly return sparse matrices. These include <em>speye</em>, <em>sprand</em>, <em>diag</em>, etc. </p> </dd> <dt>Constructed from matrices or vectors</dt> <dd><p>The function <em>sparse</em> allows a sparse matrix to be constructed from three vectors representing the row, column and data. Alternatively, the function <em>spconvert</em> uses a three column matrix format to allow easy importation of data from elsewhere. </p> </dd> <dt>Created and then filled</dt> <dd><p>The function <em>sparse</em> or <em>spalloc</em> can be used to create an empty matrix that is then filled by the user </p> </dd> <dt>From a user binary program</dt> <dd><p>The user can directly create the sparse matrix within an oct-file. </p></dd> </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 (<var>n</var>)</code> or <code>speye (<var>r</var>, <var>c</var>)</code>, which creates an <var>n</var>-by-<var>n</var> or <var>r</var>-by-<var>c</var> sparse identity matrix. </p> <p>Another typical sparse matrix that is often needed is a random distribution of random elements. The functions <em>sprand</em> and <em>sprandn</em> perform this for uniform and normal random distributions of elements. They have exactly the same calling convention, where <code>sprand (<var>r</var>, <var>c</var>, <var>d</var>)</code>, creates an <var>r</var>-by-<var>c</var> sparse matrix with a density of filled elements of <var>d</var>. </p> <p>Other functions of interest that directly create sparse matrices, are <em>diag</em> or its generalization <em>spdiags</em>, that can take the definition of the diagonals of the matrix and create the sparse matrix that corresponds to this. For example, </p> <div class="example"> <pre class="example">s = diag (sparse (randn (1,n)), -1); </pre></div> <p>creates a sparse (<var>n</var>+1)-by-(<var>n</var>+1) sparse matrix with a single diagonal defined. </p> <a name="XREFspdiags"></a><dl> <dt><a name="index-spdiags"></a><em><var>B</var> =</em> <strong>spdiags</strong> <em>(<var>A</var>)</em></dt> <dt><a name="index-spdiags-1"></a><em>[<var>B</var>, <var>d</var>] =</em> <strong>spdiags</strong> <em>(<var>A</var>)</em></dt> <dt><a name="index-spdiags-2"></a><em><var>B</var> =</em> <strong>spdiags</strong> <em>(<var>A</var>, <var>d</var>)</em></dt> <dt><a name="index-spdiags-3"></a><em><var>A</var> =</em> <strong>spdiags</strong> <em>(<var>v</var>, <var>d</var>, <var>A</var>)</em></dt> <dt><a name="index-spdiags-4"></a><em><var>A</var> =</em> <strong>spdiags</strong> <em>(<var>v</var>, <var>d</var>, <var>m</var>, <var>n</var>)</em></dt> <dd><p>A generalization of the function <code>diag</code>. </p> <p>Called with a single input argument, the nonzero diagonals <var>d</var> of <var>A</var> are extracted. </p> <p>With two arguments the diagonals to extract are given by the vector <var>d</var>. </p> <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 diagonals represented by the vector <var>d</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 the columns of <var>v</var>. </p> <p>Negative values of <var>d</var> represent diagonals below the main diagonal, and positive values of <var>d</var> diagonals above the main diagonal. </p> <p>For example: </p> <div class="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></div> <p><strong>See also:</strong> <a href="Rearranging-Matrices.html#XREFdiag">diag</a>. </p></dd></dl> <a name="XREFspeye"></a><dl> <dt><a name="index-speye"></a><em><var>s</var> =</em> <strong>speye</strong> <em>(<var>m</var>, <var>n</var>)</em></dt> <dt><a name="index-speye-1"></a><em><var>s</var> =</em> <strong>speye</strong> <em>(<var>m</var>)</em></dt> <dt><a name="index-speye-2"></a><em><var>s</var> =</em> <strong>speye</strong> <em>(<var>sz</var>)</em></dt> <dd><p>Return a sparse identity matrix of size <var>m</var>x<var>n</var>. </p> <p>The implementation is significantly more efficient than <code>sparse (eye (<var>m</var>))</code> as the full matrix is not constructed. </p> <p>Called with a single argument a square matrix of size <var>m</var>-by-<var>m</var> is created. If called with a single vector argument <var>sz</var>, this argument is taken to be the size of the matrix to create. </p> <p><strong>See also:</strong> <a href="#XREFsparse">sparse</a>, <a href="#XREFspdiags">spdiags</a>, <a href="Special-Utility-Matrices.html#XREFeye">eye</a>. </p></dd></dl> <a name="XREFspones"></a><dl> <dt><a name="index-spones"></a><em><var>r</var> =</em> <strong>spones</strong> <em>(<var>S</var>)</em></dt> <dd><p>Replace the nonzero entries of <var>S</var> with ones. </p> <p>This creates a sparse matrix with the same structure as <var>S</var>. </p> <p><strong>See also:</strong> <a href="#XREFsparse">sparse</a>, <a href="#XREFsprand">sprand</a>, <a href="#XREFsprandn">sprandn</a>, <a href="#XREFsprandsym">sprandsym</a>, <a href="Function-Application.html#XREFspfun">spfun</a>, <a href="Information.html#XREFspy">spy</a>. </p></dd></dl> <a name="XREFsprand"></a><dl> <dt><a name="index-sprand"></a><em></em> <strong>sprand</strong> <em>(<var>m</var>, <var>n</var>, <var>d</var>)</em></dt> <dt><a name="index-sprand-1"></a><em></em> <strong>sprand</strong> <em>(<var>m</var>, <var>n</var>, <var>d</var>, <var>rc</var>)</em></dt> <dt><a name="index-sprand-2"></a><em></em> <strong>sprand</strong> <em>(<var>s</var>)</em></dt> <dd><p>Generate a sparse matrix with uniformly distributed random values. </p> <p>The size of the matrix is <var>m</var>x<var>n</var> with a density of values <var>d</var>. <var>d</var> must be between 0 and 1. Values will be uniformly distributed on the interval (0, 1). </p> <p>If called with a single matrix argument, a sparse matrix is generated with random values wherever the matrix <var>s</var> is nonzero. </p> <p>If called with a scalar fourth argument <var>rc</var>, a random sparse matrix with reciprocal condition number <var>rc</var> is generated. If <var>rc</var> is a vector, then it specifies the first singular values of the generated matrix (<code>length (<var>rc</var>) <= min (<var>m</var>, <var>n</var>)</code>). </p> <p><strong>See also:</strong> <a href="#XREFsprandn">sprandn</a>, <a href="#XREFsprandsym">sprandsym</a>, <a href="Special-Utility-Matrices.html#XREFrand">rand</a>. </p></dd></dl> <a name="XREFsprandn"></a><dl> <dt><a name="index-sprandn"></a><em></em> <strong>sprandn</strong> <em>(<var>m</var>, <var>n</var>, <var>d</var>)</em></dt> <dt><a name="index-sprandn-1"></a><em></em> <strong>sprandn</strong> <em>(<var>m</var>, <var>n</var>, <var>d</var>, <var>rc</var>)</em></dt> <dt><a name="index-sprandn-2"></a><em></em> <strong>sprandn</strong> <em>(<var>s</var>)</em></dt> <dd><p>Generate a sparse matrix with normally distributed random values. </p> <p>The size of the matrix is <var>m</var>x<var>n</var> with a density of values <var>d</var>. <var>d</var> must be between 0 and 1. Values will be normally distributed with a mean of 0 and a variance of 1. </p> <p>If called with a single matrix argument, a sparse matrix is generated with random values wherever the matrix <var>s</var> is nonzero. </p> <p>If called with a scalar fourth argument <var>rc</var>, a random sparse matrix with reciprocal condition number <var>rc</var> is generated. If <var>rc</var> is a vector, then it specifies the first singular values of the generated matrix (<code>length (<var>rc</var>) <= min (<var>m</var>, <var>n</var>)</code>). </p> <p><strong>See also:</strong> <a href="#XREFsprand">sprand</a>, <a href="#XREFsprandsym">sprandsym</a>, <a href="Special-Utility-Matrices.html#XREFrandn">randn</a>. </p></dd></dl> <a name="XREFsprandsym"></a><dl> <dt><a name="index-sprandsym"></a><em></em> <strong>sprandsym</strong> <em>(<var>n</var>, <var>d</var>)</em></dt> <dt><a name="index-sprandsym-1"></a><em></em> <strong>sprandsym</strong> <em>(<var>s</var>)</em></dt> <dd><p>Generate a symmetric random sparse matrix. </p> <p>The size of the matrix will be <var>n</var>x<var>n</var>, with a density of values given by <var>d</var>. <var>d</var> must be between 0 and 1 inclusive. Values will be normally distributed with a mean of zero and a variance of 1. </p> <p>If called with a single matrix argument, a random sparse matrix is generated wherever the matrix <var>s</var> is nonzero in its lower triangular part. </p> <p><strong>See also:</strong> <a href="#XREFsprand">sprand</a>, <a href="#XREFsprandn">sprandn</a>, <a href="#XREFspones">spones</a>, <a href="#XREFsparse">sparse</a>. </p></dd></dl> <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, </p> <div class="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></div> <p>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> <p>The function <em>spconvert</em> 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: </p> <div class="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></div> <p>An example of creating and filling a matrix might be </p> <div class="example"> <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></div> <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 <em>spalloc</em> 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. </p> <a name="XREFfull"></a><dl> <dt><a name="index-full"></a><em><var>FM</var> =</em> <strong>full</strong> <em>(<var>SM</var>)</em></dt> <dd><p>Return a full storage matrix from a sparse, diagonal, or permutation matrix, or a range. </p> <p><strong>See also:</strong> <a href="#XREFsparse">sparse</a>, <a href="Information.html#XREFissparse">issparse</a>. </p></dd></dl> <a name="XREFspalloc"></a><dl> <dt><a name="index-spalloc"></a><em><var>s</var> =</em> <strong>spalloc</strong> <em>(<var>m</var>, <var>n</var>, <var>nz</var>)</em></dt> <dd><p>Create an <var>m</var>-by-<var>n</var> sparse matrix with pre-allocated space for at most <var>nz</var> nonzero elements. </p> <p>This is useful for building a matrix incrementally by a sequence of indexed assignments. Subsequent indexed assignments after <code>spalloc</code> will reuse the pre-allocated memory, provided they are of one of the simple forms </p> <ul> <li> <code><var>s</var>(I:J) = <var>x</var></code> </li><li> <code><var>s</var>(:,I:J) = <var>x</var></code> </li><li> <code><var>s</var>(K:L,I:J) = <var>x</var></code> </li></ul> <p><b>and</b> that the following conditions are met: </p> <ul> <li> the assignment does not decrease nnz (<var>S</var>). </li><li> after the assignment, nnz (<var>S</var>) does not exceed <var>nz</var>. </li><li> no index is out of bounds. </li></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 a contiguous block of columns. </p> <p>The amount of pre-allocated memory for a given matrix may be queried using the function <code>nzmax</code>. </p> <p><strong>See also:</strong> <a href="Information.html#XREFnzmax">nzmax</a>, <a href="#XREFsparse">sparse</a>. </p></dd></dl> <a name="XREFsparse"></a><dl> <dt><a name="index-sparse"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>a</var>)</em></dt> <dt><a name="index-sparse-1"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>i</var>, <var>j</var>, <var>sv</var>, <var>m</var>, <var>n</var>)</em></dt> <dt><a name="index-sparse-2"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>i</var>, <var>j</var>, <var>sv</var>)</em></dt> <dt><a name="index-sparse-3"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>m</var>, <var>n</var>)</em></dt> <dt><a name="index-sparse-4"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>i</var>, <var>j</var>, <var>s</var>, <var>m</var>, <var>n</var>, "unique")</em></dt> <dt><a name="index-sparse-5"></a><em><var>s</var> =</em> <strong>sparse</strong> <em>(<var>i</var>, <var>j</var>, <var>sv</var>, <var>m</var>, <var>n</var>, <var>nzmax</var>)</em></dt> <dd><p>Create a sparse matrix from a full matrix, or row, column, value triplets. </p> <p>If <var>a</var> is a full matrix, convert it to a sparse matrix representation, removing all zero values in the process. </p> <p>Given the integer index vectors <var>i</var> and <var>j</var>, and a 1-by-<code>nnz</code> vector of real or complex values <var>sv</var>, construct the sparse matrix <code>S(<var>i</var>(<var>k</var>),<var>j</var>(<var>k</var>)) = <var>sv</var>(<var>k</var>)</code> with overall dimensions <var>m</var> and <var>n</var>. If any of <var>sv</var>, <var>i</var> or <var>j</var> are scalars, they are expanded to have a common size. </p> <p>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 <code><var>m</var> = max (<var>i</var>)</code>, <code><var>n</var> = max (<var>j</var>)</code>. </p> <p><strong>Note</strong>: if multiple values are specified with the same <var>i</var>, <var>j</var> indices, the corresponding value in <var>s</var> will be the sum of the values at the repeated location. See <code>accumarray</code> for an example of how to produce different behavior, such as taking the minimum instead. </p> <p>If the option <code>"unique"</code> is given, and more than one value is specified at the same <var>i</var>, <var>j</var> indices, then the last specified value will be used. </p> <p><code>sparse (<var>m</var>, <var>n</var>)</code> will create an empty <var>m</var>x<var>n</var> sparse matrix and is equivalent to <code>sparse ([], [], [], <var>m</var>, <var>n</var>)</code> </p> <p>The argument <var>nzmax</var> is ignored but accepted for compatibility with <small>MATLAB</small>. </p> <p>Example 1 (sum at repeated indices): </p> <div class="example"> <pre class="example"><var>i</var> = [1 1 2]; <var>j</var> = [1 1 2]; <var>sv</var> = [3 4 5]; sparse (<var>i</var>, <var>j</var>, <var>sv</var>, 3, 4) ⇒ Compressed Column Sparse (rows = 3, cols = 4, nnz = 2 [17%]) (1, 1) -> 7 (2, 2) -> 5 </pre></div> <p>Example 2 ("unique" option): </p> <div class="example"> <pre class="example"><var>i</var> = [1 1 2]; <var>j</var> = [1 1 2]; <var>sv</var> = [3 4 5]; sparse (<var>i</var>, <var>j</var>, <var>sv</var>, 3, 4, "unique") ⇒ Compressed Column Sparse (rows = 3, cols = 4, nnz = 2 [17%]) (1, 1) -> 4 (2, 2) -> 5 </pre></div> <p><strong>See also:</strong> <a href="#XREFfull">full</a>, <a href="Accumulation.html#XREFaccumarray">accumarray</a>, <a href="#XREFspalloc">spalloc</a>, <a href="#XREFspdiags">spdiags</a>, <a href="#XREFspeye">speye</a>, <a href="#XREFspones">spones</a>, <a href="#XREFsprand">sprand</a>, <a href="#XREFsprandn">sprandn</a>, <a href="#XREFsprandsym">sprandsym</a>, <a href="#XREFspconvert">spconvert</a>, <a href="Function-Application.html#XREFspfun">spfun</a>. </p></dd></dl> <a name="XREFspconvert"></a><dl> <dt><a name="index-spconvert"></a><em><var>x</var> =</em> <strong>spconvert</strong> <em>(<var>m</var>)</em></dt> <dd><p>Convert a simple sparse matrix format easily generated by other programs into Octave’s internal sparse format. </p> <p>The input <var>m</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> <p><strong>See also:</strong> <a href="#XREFsparse">sparse</a>. </p></dd></dl> <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. See <a href="External-Code-Interface.html#External-Code-Interface">External Code Interface</a>, for a full description of the techniques involved. </p> <hr> <div class="header"> <p> Next: <a href="Information.html#Information" accesskey="n" rel="next">Information</a>, Previous: <a href="Storage-of-Sparse-Matrices.html#Storage-of-Sparse-Matrices" accesskey="p" rel="prev">Storage of Sparse Matrices</a>, Up: <a href="Basics.html#Basics" accesskey="u" rel="up">Basics</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>