## Sparse Matrices

Sparse matrices are constructed using the sparse function. The most general calling sequence is sparse( u, v, w, m, n, max ) where u, v, and w are row vectors each of the same dimension, m and n are the dimensions of the matrix, and max is the maximum number of elements the matrix is expected to store. If we designate the matrix A, then the entries of the matrix are assigned as follows:

```>> for i=1:length(u),
A(u(i), v(i)) = w(i)
end
```

For example, the following creates a 20x20 matrix, with room for 30 entries, and fills that matrix with 10 values:

```>> A = sparse( 1:10, 3:13, linspace( 1.53, 23.5, 10 ), 20, 20, 30 )

A =

(1,3)       1.5300
(2,4)       3.9711
(3,5)       6.4122
(4,6)       8.8533
(5,7)      11.2944
(6,8)      13.7356
(7,9)      16.1767
(8,10)     18.6178
(9,11)     21.0589
(10,12)     23.5000

```

If you do not intend to change any values in a matrix, the last argument need not be specified, in which case, it will allocate as room for as many objects as there are in the initial three vectors.

```>> A = sparse( 1:10, 3:13, linspace( 1.53, 23.5, 10 ), 20, 20 ); % same as sparse( 1:10, 3:13, linspace( 1.53, 23.5, 10 ), 20, 10 )
```

Unfortunately, if you now assign one more value, e.g., A(1,1) = 3, it must allocate an new larger block of memory. It will double the number of stored elements, so this memory allocation will not need to be performed at each new allocation. Consider:

```>> A = sparse( 1:10, 2:11, 3:12, 20, 20, 12 );
>> B = sparse( 1:10, 2:11, 3:12, 20, 20 ); % defaults to storing 10 objects
>> whos
Name      Size           Bytes  Class

A        20x20             228  sparse array
B        20x20             204  sparse array

Grand total is 22 elements using 432 bytes

>> A(1,5) = 3;
>> B(1,5) = 3;
>> whos
Name      Size           Bytes  Class

A        20x20             228  sparse array
B        20x20             324  sparse array

Grand total is 32 elements using 552 bytes

```

Note that the space allocated for matrix B has jumped to size 324.

Converting a matrix into a sparse matrix is as easy as:

```>> D = diag( 5:20 );
>> sparse( D );
```

You can find out about sparse functions by entering help sparfun at the prompt. Some examples are speye (a sparse eye function), eigs (a sparse eigenvalue function), normest (find an estimate of the norm), and condest (find an estimate of the condition number.)