### 14.4.2 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 14.4.1). The matrix command (see Section 14.2.4) or the convert command (see Section 10.1.10) can then turn the table into a matrix.

#### Example

First, define the non-zero elements.

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]

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.

a:=convert(A,array)

or:

a:=matrix(A)

⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ |
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
| ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦