Often it is desirable to work with parts or separate elements of matrices. Hereto, each element of a matrix can be accessed by means of indices. The command for this has the general form >> A(m,n). Here $ A$ is the matrix of which the element with row index $ m$ and column index $ n$ is being specified. If $ A$ is a vector, one index suffices. For the matrix $ A$ in exercise 4.1, >> A(3,2) gives the value of this element, namely $ -2$ . Among others, this enables you to change one single element in the matrix. The command:

>> A(3,2) = 3

changes the original value -2 of the element on the third row and second column of $ A$ into the new value 3. All other elements of $ A$ remain the same. Instead of indicating one element of $ A$ , you can also indicate more elements of $ A$ at the same time. This is done by giving a vector of indices instead of one single index.

>> A(3,[2 4])

gives the elements $ a_{32}$ and $ a_{34}$ from $ A$ arranged as in $ A$ , i.e., as a 1 x 2 matrix. Hence, the command

>> B=A([1 2 3],[2 4])

gives the 3 x 2 matrix consisting of the elements of $ A$ in the first three rows and columns two and four of $ A$ . For example, applying the previously mentioned command on a $ 4\times 4$ matrix

$\displaystyle A=\begin{bmatrix}a_{11} & a_{12} & a_{13}& a_{14} \\
a_{21} & a...
...31} & a_{32} & a_{33}& a_{34}\\
a_{41} & a_{42} & a_{43}& a_{44}\end{bmatrix}$

results in

$\displaystyle B=\begin{bmatrix}a_{12} & a_{14}\\
a_{22} & a_{24}\\
a_{32} & a_{24}\end{bmatrix}.$

In view of the remarks from paragraph 4.2.4, this could also have been accomplished with the command

>> A(1:3,[2 4])

When only `:' is used, all rows or columns are meant. This can appear in the following forms:

  • A(:,j) is the $ j^{\rm th}$ column of $ A$ .
  • A(i,:) is the $ i^{\rm th}$ row of $ A$ .
  • A(:,:) is the same as $ A$ .
This possibility is especially useful if you want to perform operations with whole rows or columns at once. For example, for our original matrix $ A$ , the command:

>> A(2,:)-7*A(1,:)

gives the row vector that results from subtracting seven times the first row of $ A$ from the second row of $ A$ . With the command:

>> A(2,:) = A(2,:)-7*A(1,:)

the same result is calculated and assigned to the second row of $ A$ . Thus, this command has changed the matrix $ A$ .

Previous      Next      Up      Contents

Esteur 2010-03-22