Skip to main content

Section 2.2 More tools for constructing matrices

The number of coefficients in a linear system grows rapidly with its size: a system with 20 equations and 20 variables has a matrix with 400 coefficients. Entering these by hand would be tedious. We already have two ways to construct large matrices: zeros(m, n) and ones(m, n) but these are not invertible matrices. This section presents two other useful constructions.

The identity matrix is usually denoted \(I\) in mathematics, or \(I_n\) if it is necessary to emphasize its size. For example,

\begin{equation*} I_3 = \begin{pmatrix} 1 \amp 0\amp 0 \\ 0\amp 1\amp 0 \\ 0\amp 0\amp 1 \end{pmatrix} \end{equation*}

In Matlab this matrix would be created as eye(3). The name of the command was chosen because “eye” is pronounced the same as “I”. We also get scalars multiples of the identity matrix, for example 5*eye(3) is

\begin{equation*} \begin{pmatrix} 5 \amp 0\amp 0 \\ 0\amp 5\amp 0 \\ 0\amp 0\amp 5 \end{pmatrix} \end{equation*}

A diagonal matrix has zeros everywhere except on the main diagonal. The identity matrix \(I\) is a special case of a diagonal matrix. In Matlab, the command diag(v) creates a diagonal matrix which has the elements of vector v on its main diagonal. For example, diag([6 -4 7]) creates the matrix

\begin{equation*} \begin{pmatrix} 6 \amp 0\amp 0 \\ 0\amp -4\amp 0 \\ 0\amp 0\amp 7 \end{pmatrix} \end{equation*}

Some problems in engineering and in differential equations lead to matrices where nonzero coefficients are close to the main diagonal but not exactly at it: for example,

\begin{equation*} \begin{pmatrix} 2 \amp -1 \amp 0\amp 0 \amp 0 \\ -1 \amp 2 \amp -1\amp 0 \amp 0 \\ 0 \amp -1 \amp 2\amp -1 \amp 0 \\ 0 \amp 0 \amp -1\amp 2 \amp -1 \\ 0 \amp 0 \amp 0\amp -1 \amp 2 \\ \end{pmatrix} \end{equation*}

To construct such matrices we can use diag(v, k) which places the elements of vector v on the diagonal parallel to the main one but \(k\) positions above it. So, diag(v, 1) is just above the main diagonal and diag(v, -1) is just below. The matrix shown above could be formed as

 diag([2 2 2 2 2]) - diag([1 1 1 1], 1) - diag([1 1 1 1], -1)

This is an example of a tridiagonal matrix: there are only three diagonals with nonzero entries. More generally, a matrix is called sparse if most of its elements are 0. Large sparse matrices frequently arise in computations.

Let \(A\) be the 9×9 matrix with -1 on the main diagonal and 1 above it. Find and display the products of \(A\) with its transpose: \(A^TA\) and \(AA^T\text{.}\)

Answer
A = diag(ones(1, 8), 1) - eye(9);
disp(A'*A)
disp(A*A')

The two products are very similar but are not quite the same.