Skip to main content

Section 2.3 Array operations

Matlab supports array operations in which the input data is placed into an array (usually a vector or a matrix) and some mathematical operation is carried out on all of the data at once. For example, to get the square roots of the first 25 positive integers we can execute

sqrt(1:25)

with the result

[1.0000 1.4142 1.7321 2.0000 2.2361 ... 4.8990 5.0000]

More generally, if v is a vector of nonnegative numbers, then sqrt(v) has the roots of those numbers. Other functions like sin and exp work the same way. The benefts of array operations are more compact code and faster execution.

Suppose v = [5 2 -3] and we want to get the squares of the elements of v. By analogy with the above, we try v^2 but get an error. The problem is that squaring v is understood as v*v which in Matlab means multiplication according to the rules of Section 1.4. The row vector v is treated as a matrix of size 1×3. And one cannot multiply a 1×3 matrix by another 1×3 matrix: the inner dimensions do not match. But we just want elementwise squaring, not any kind of matrix multiplication. To tell Matlab this, put a period . before the operation character: v.^2 gives [25 4 9]. Similarly, .* and ./ are used for elementwise multiplication and division: [3 4].*[2 -5] is [6 -20] and [3 4]./[2 -5] is [1.5 -0.8]. We never need a period in front of + or - because these operations are always performed elementwise.

Summary: without a preceding period, *, / and ^ refer to what we do with matrices and vectors in linear algebra. Adding a period tells Matlab to forget about linear algebra and handle each term individually. Compare two ways to multiply the matrices

\begin{equation*} A = \begin{pmatrix} 3 \amp -2 \\ 2 \amp 5\end{pmatrix}, \quad B = \begin{pmatrix} -5 \amp 4 \\ 1 \amp 3\end{pmatrix} \end{equation*}

The command

[3 -2; 2 5] * [-5 4; 1 3]

produces

\begin{equation*} \begin{pmatrix} -17 \amp 6 \\ -5 \amp 23 \end{pmatrix} \end{equation*}

which is the matrix product according to linear algebra. The command

[3 -2; 2 5] .* [-5 4; 1 3]

produces

\begin{equation*} \begin{pmatrix} -15 \amp -8 \\ 2\amp 15 \end{pmatrix} \end{equation*}

which is the elementwise product: it would be considered a wrong way to multiply matrices in a linear algebra course.

Use array operations to display the numbers \(n^{1/n}\) for \(n=1, \dots, 10\text{.}\) What value of \(n\) has the largest such root?

Answer
v = 1:10;
disp(v.^(1./v))

The root is largest for \(n = 3\text{.}\)

Note that both periods are necessary. Without the second one, Matlab would try to interpet 1/v as a linear system with coefficients v and right hand side 1, which is not what we want. With 1./v we get the vector [1/1 1/2 1/3 ...]. Similarly, without the first period Matlab would try to interpret v^(...) as a matrix power, which would not make sense either.