Skip to main content

Section 3.1 Built-in functions

Mathematical functions in Matlab have recognizable names: sqrt, log (meaning natural logarithm, base e), exp, abs (absolute value), sin, cos and so on. They can be applied to vectors or matrices elementwise: for example exp([1 2 3]) returns a vector with components \(e^1, e^2, e^3\text{.}\)

There are also aggregate functions which are useful for summarizing data. The most important of these are sum (sum of values), max (maximum) and min (minimum). When applied to a vector, these functions return a single number. So, if v = [3 1 4 1] then sum(v) is 9, max(v) is 4, and min(v) is 1.

Find the sum of cubes of the integers from 1 to 10.

Answer
sum((1:10).^3)

Note that the parentheses are important here: sum(1:10.^3) would be the sum of all integers from 1 to 1000.

Aggregate functions get more complicated (and powerful) when they are applied to matrices. In this case they do not return a single number. Given a matrix A, for example A = [3 9; 5 2], we can find its:

  • Column sums with sum(A, 1): the result is a row vector [8 11] which contains the sum of each column.
  • Row sums with sum(A, 2): the result is a column vector [12; 7] which contains the sum of each row.

The second argument (1 or 2) means that we sum along the 1st index (row index) or 2nd index (column index). Summing along the row index means A(1, 1) + A(2, 1) + A(3, 1) + ... which produces the sum within each column. Entering sum(A) has the same effect as sum(A, 1).

Stacking the columns of a matrix. When we want the sum (or another aggregate function) of all entries of matrix A, we can stack the columns of A using a single colon: A(:). Then an aggregate function can be applied to this column. For example, if A = [1 2; 3 4] then A(:) is the column [1; 3; 2; 4] and sum(A(:)) is 10.

Given a matrix, such as A = [3 6; -8 4; 10 1] find its “maximal absolute row sum”, meaning add up the absolute values of the elements within each row, and take the maximum of the results.

Answer
max(sum(abs(A), 2))

The result is 12, coming from the second row. The maximal absolute row sum is important in applied linear algebra. It is one of several norms that can be defined for a matrix.