Function returns quadratic matrix in R [closed]

You could do

n <- 3
mat <- matrix(nrow = n, ncol = n)
pmax(row(mat), col(mat)) ^ 2
#     [,1] [,2] [,3]
#[1,]    1    4    9
#[2,]    4    4    9
#[3,]    9    9    9

Turn this into a function

f1 = function(n = 2) {
  mat <- matrix(nrow = n, ncol = n)
  pmax(row(mat), col(mat)) ^ 2
}

f1()
#     [,1] [,2]
#[1,]    1    4
#[2,]    4    4

A second option using outer

f2 <- function(n = 3) {
  tmp <- (1:n)^2
  outer(tmp, tmp, pmax)
}

Leave a Comment