Defining sparse matrices

### 5.46.1 Defining sparse matrices

A matrix is sparse if most of its elements are 0. To specify a sparse matrix, it is easier to define the non-zero elements. This can be done with a table (see Section 5.43). The matrix command (see Section 5.44.4) or the convert command (see Section 5.23.26) can then turn the table into a matrix.

#### Example.

First, define the non-zero elements.
Input:

A:= table((0,0)=1, (1,1)=2, (2,2)=3, (3,3) = 4, (4,4) = 5)

or:

purge(A)
A[0..4,0..4]:=[1,2,3,4,5]

Output:

Key | Value
⎛ ⎝ | 0,0 | ⎞ ⎠
| 1
⎛ ⎝ | 1,1 | ⎞ ⎠
| 2
⎛ ⎝ | 2,2 | ⎞ ⎠
| 3
⎛ ⎝ | 3,3 | ⎞ ⎠
| 4
⎛ ⎝ | 4,4 | ⎞ ⎠
| 5

This table can be converted to a matrix with either the convert command or the matrix command.
Input:

a:= convert(A,array)

or:

a:= matrix(A)

Output:

⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ |
1 | 0 | 0 | 0 | 0
0 | 2 | 0 | 0 | 0
0 | 0 | 3 | 0 | 0
0 | 0 | 0 | 4 | 0
0 | 0 | 0 | 0 | 5
| ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦