Programming

Accessing Multiple Elements

For the 4-by-4 matrix `A` shown below, it is possible to compute the sum of the elements in the fourth column of `A` by typing

• ```A = magic(4);
A(1,4) + A(2,4) + A(3,4) + A(4,4)
```

You can reduce the size of this expression using the colon operator. Subscript expressions involving colons refer to portions of a matrix. The expression

• ```A(1:m, n)
```

refers to the elements in rows `1` through `m` of column `n` of matrix `A`. Using this notation, you can compute the sum of the fourth column of `A` more succinctly:

• ``````sum(A(1:4, 4))
``````

Nonconsecutive Elements

To refer to nonconsecutive elements in a matrix, use the colon operator with a step value. The `m:3:n` in this expression means to make the assignment to every third element in the matrix. Note that this example uses linear indexing:

• ```B = A;

B(1:3:16) = -10
B =
-10     2     3   -10
5    11   -10     8
9   -10     6    12
-10    14    15   -10
```

The end Keyword

MATLAB provides a keyword called `end` that designates the last element in the dimension in which it appears. This keyword can be useful in instances where your program doesn't know how many rows or columns there are in a matrix. You can replace the expression in the previous example with

• ```B(1:3:end) = -10
```

 Note    The keyword `end` has two meanings in MATLAB. It can be used as explained above, or to terminate a certain block of code (e.g., `if` and `for` blocks).

Specifying All Elements of a Row or Column

The colon by itself refers to all the elements in a row or column of a matrix. Using the following syntax, you can compute the sum of all elements in the second column of a 4-by-4 magic square `A`:

• ```sum(A(:, 2))
ans =
34
```

By using the colon with linear indexing, you can refer to all elements in the entire matrix. This example displays all the elements of matrix `A`, returning them in a column-wise order:

• ```A(:)
ans =
16
5
9
4
.
.
.
12
1
```

Using a Matrix As an Index

You can repeatedly access an array element using the `ones` function. To create a new 2-by-6 matrix out of the ninth element of a 4-by-4 magic square `A`,

• ```B = A(9 * ones(2, 6))
B =
3     3     3     3     3     3
3     3     3     3     3     3
```

 Functions That Control Indexing Style Logical Indexing