Skip to main content

Section 1.4 Operations on vectors and matrices

Addition and subtraction works the same way as it does in Linear Algebra. If two vectors, or two matrices, have the same size, they can be added or subtracted. For example:

    x = [3 7 2];
    y = [8 -2 0];
    z = x + y;

results in z being [11 5 2]. But we cannot add [8 -2] and [2 5 8] because these vectors have different sizes.

Scalar multiplication also works as expected: with x as above, 3*x is the vector [9 21 6].

One can also multiply two vectors, or two matrices, or a vector and a matrix. To understand how this works in Matlab, keep in mind that a vector is treated as a matrix with one row (or one column). Two matrices can be multiplied only when the inner dimensions agree: that is, two matrices of sizes \(m\times n\) and \(p\times q\) can be multiplied when \(n = p\text{.}\) The product has size \(m\times q\text{.}\) Some examples:

  • [3 7] * [4 2] is an error: the first argument has size \(1\times 2\text{,}\) the second also has size \(1\times 2\text{,}\) and the inner dimensions do not agree: \(2\ne 1\text{.}\)
  • [3 7] * [4; 2] is 26. the first argument has size \(1\times 2\text{,}\) the second has size \(2\times 1\text{,}\) so the product is defined and has size \(1\times 1\) which makes it a scalar. This is how one computes the scalar product of two vectors: it comes from multiplying a row vector by a column vector. In introductory mathematics courses this product is called the dot product which emphasizes its notation instead of output. This may be confusing because Matlab also has products with a dot . but they mean a different thing: we will see them in next chapter.
  • [1 2 3; 4 5 6] * [-4; 0; 3] is [5; 2]. The sizes \(2\times 3\) and \(3\times 1\) are compatible and the product has size \(2\times 1\text{.}\) This is how matrix-vector products work in linear algebra too: the vector, placed to the right of a matrix, must be written as a column.
  • [5 -2] * [1 2 3; 4 5 6] is [-3 0 3]. The sizes \(1\times 2\) and \(2\times 3\) are compatible and the product has size \(1\times 3\text{.}\) So, we can have a vector to the left of a matrix when it is a row vector.
  • [0 1; -1 0] * [1 2 3; 4 5 6] is [4 5 6; -1 -2 -3]. This is a matrix product. Two matrices have compatible sizes \(2\times 2\) and \(2\times 3\text{,}\) and the product is of size \(2\times 3\text{.}\)

Write a script which illustrates that the product of two 2×2 matrices depends on their order.

Answer
A = [1 2; 3 4];
B = [5 6; 7 8];
disp(A*B)
disp(B*A)

Remark: the particular numbers are not important: if you fill two square matrices with random nonzero numbers, you will probably find their product depends on the order of term.