Matrices

Matrix representation and projection.

Matrix

There is no multi-dimensional arrays in Swan, only arrays of arrays. In Swan, A of type T^M^N means that A is an array of size N where each cell is an array of size M. It represents a matrix of M columns and N rows.

The element aij (the element at row i and column j) in A of type T^M^N is accessed by A[i][j] with 0<=i<N and 0<=j<M. Indeed, the array indexes start from 0, and projections in multi-dimensional arrays are read from left to right.

For example, the matrix A = \[ \left[ {\begin{array}{ccccc} 1 & 2 & 3 & 4 & 5 \\2 & 1 & 4 & 1 & 3\\ 2 & 2 & 3 & 2 & 2 \end{array}} \right] \] is of type int32^5^3 and represented by an array of size 3 where each element is an array of size 5: [[1,2,3,4,5], [2,1,4,1,3], [2,2,3,2,2]].

In this matrix, the element a12 is accessed by the projection A[0][1] in Swan. The projection A[0] accesses the first array [1,2,3,4,5] and in this first array, the projection index 1 returns the number 2.

Note: The declaration of a matrix of N rows and M columns is done in reverse order with respect to the C language.
Table 1.
LanguageDeclarationprojection
C
int32 A[N][M]
A[i][j]
Swan
A: int32^M^N
A[i][j]
The projections to access an element at row i and column j are done in the same order as in C-language, row and column, then A[i][j].

Matrix Transposition

The transposition of a matrix A with N rows and M columns is defined by B = A^T where the N rows of A becomes the N columns of B (and then the M columns of A becomes the M rows).

In Swan, transpose A with A of type T^M^N defines a matrix of type T^N^M, where the N rows and M columns of A have been inverted. The expression transpose(A)[i][j] is equal to A[j][i].

For example, B = transpose(A) with A from the previous example defines the matrix: B = A^T=\[ \left[ {\begin{array}{ccc} 1 & 2 & 2\\ 2&1& 2\\3 & 4 & 3\\4 &1&2\\ 5 & 3 & 2\end{array}} \right] \]

In Swan, B is of type int32^3^5 and represented by an array of size 5 where each element is an array of size 3: [[1,2,2], [2,1,2], [3,4,3], [4,1,2], [5,3,2]].

Note: In Swan, A of type T^M^N is represented by rows. This representation allows to access a matrix row by row, and then in each row the inner element. To access the array column by column, the array can be transposed or a forward construct with direct access through suitable indices can be used (for example, see The Matrix-Matrix Product).