Create a matrix
outer
takes two
vectors and a function (that itself takes two arguments) and builds a
matrix by calling the given function for each combination of the elements in the two vectors.
x <- 0:2; # three columns
y <- 0:4; # five rows
m <- outer (
y, # First dimension: the columns (y)
x, # Second dimension: the rows (x)
function (x, y) x+2*y
);
class(m);
#
# "matrix"
#
dim(m);
#
# 3 5
print(m);
#
# [,1] [,2] [,3]
# [1,] 0 2 4
# [2,] 1 3 5
# [3,] 2 4 6
# [4,] 3 5 7
# [5,] 4 6 8
Using an operator instead of a function
In place of the function, an
operator can be given which makes it easy to create a matrix with simple calculations (such as multiplying):
o <- outer(c(10, 20, 30), c(2, 4, 6), "*")
print(o)
# [,1] [,2] [,3]
# [1,] 20 40 60
# [2,] 40 80 120
# [3,] 60 120 180
Using outer to create a grid for plotting
x <- y <- seq(-1, 1, len=51);
grid <- outer(
x,
y,
function(x, y) {
sin(x) * exp(y)
}
);
filled.contour(grid, axes = FALSE, color.palette=rainbow, asp=1);