Skip to main content

Section 2.4 Implicit expansion of arrays

Sometimes we can apply an elementwise array operation to two arrays of different sizes. The rule is that the array sizes must match, but number 1 matches any number. For example, the following commands work, and produce a 3×5 matrix of 2s:

  • ones(3, 1) + ones(3, 5)
  • ones(1, 5) + ones(3, 5)
  • ones(1, 5) + ones(3, 1)

The reason is that a matrix with 1 column can be turned into a matrix with 5 columns just by repeating the same column 5 times. This kind of expansion by repetition creates 3×5 matrices in each of the above examples. For a more interesting example, try (1:6) + (1:6)' - 1 which combines a row vector (size 1×6) with a column vector (size 6×1) and a scalar (size 1×1). The array expansion results in a neat 6×6 matrix:

1     2     3     4     5     6
2     3     4     5     6     7
3     4     5     6     7     8
4     5     6     7     8     9
5     6     7     8     9    10
6     7     8     9    10    11

In contrast, ones(3, 2) + ones(3, 5) does not work: the numbers 2 and 5 are not equal, and neither of them is 1.

Display the multiplication table of size 9×9, that is a matrix of products of integers from 1 to 9.

Answer
A = (1:9).*(1:9)';
disp(A)

The output is shown below.

1     2     3     4     5     6     7     8     9
2     4     6     8    10    12    14    16    18
3     6     9    12    15    18    21    24    27
4     8    12    16    20    24    28    32    36
5    10    15    20    25    30    35    40    45
6    12    18    24    30    36    42    48    54
7    14    21    28    35    42    49    56    63
8    16    24    32    40    48    56    64    72
9    18    27    36    45    54    63    72    81

Note that without the period we would get the single number 285 instead. (Why this number?)