Matrix Operations

June 22, 2010

Our Standard Prelude provides a matrix datatype with create, lookup and setting operations. In today’s exercise we extend the matrix datatype with some mathematical operations: sum two matrices, multiply a matrix by a scalar, multiply two matrices, and transpose a matrix.

  • Addition of two matrices is done by adding elements in corresponding positions, assuming identical dimensions. For example:

    \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} + \begin{pmatrix} 2 & 3 & 4 \\ 3 & 4 & 5 \end{pmatrix} = \begin{pmatrix} 3 & 5 & 7 \\ 7 & 9 & 11 \end{pmatrix}

  • Multiplying a scalar times a matrix is done by multiplying the scalar times each element in turn. For example:

    2 \times \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix}  = \begin{pmatrix} 2 & 4 & 6 \\ 8 & 10 & 12 \end{pmatrix}

  • The product of an m×n matrix A and an n×p matrix B is the m×p matrix C whose entries are defined by C_{i,j} = \sum_{k=0}^{n-1} A_{i,k} \times B_{k,j}. For example:

    \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix} \times \begin{pmatrix} 1 & 2 & 3 & 4 \\ 2 & 3 & 4 & 5 \\ 3 & 4 & 5 & 6 \end{pmatrix} = \begin{pmatrix} 14 & 20 & 26 & 32 \\ 32 & 47 & 62 & 77 \end{pmatrix}

  • The transpose of a matrix interchanges the rows and columns of a matrix. For example:

    \begin{pmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \end{pmatrix}^{T} = \begin{pmatrix}1 & 4 \\ 2 & 5 \\ 3 & 6 \end{pmatrix}

Your task is to write functions that perform the four matrix operations described above. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisement

Pages: 1 2