3

Does anyone know a fast way to create a matrix like the following one in R.

     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    2    2    2
[3,]    1    2    3    3
[4,]    1    2    3    4

The matrix above is 4x4 and I want to create something like 10000x10000.

1
  • @CarlWitthoft. OP just wants a 4-by-4 matrix. & is just a field separator like some languages (e.g. LaTeX) use. I have edited the question.
    – flodel
    Commented Jul 9, 2013 at 19:15

1 Answer 1

13

You can do:

N <- 4
m <- matrix(nrow = N, ncol = N)
m[] <- pmin.int(col(m), row(m))

or a shorter version as suggested by @dickoa:

m <- outer(1:N, 1:N, pmin.int)

These also work and are both faster:

m <- pmin.int(matrix(1:N, nrow = N, byrow = TRUE),
              matrix(1:N, nrow = N, byrow = FALSE))

m <- matrix(pmin.int(rep(1:N, each = N), 1:N), nrow = N)

Finally, here is a cute one using a matrix product but it is rather slow:

x <- matrix(1, N, N)
m <- lower.tri(x, diag = TRUE) %*% upper.tri(x, diag = TRUE)

Note that a 10k-by-10k matrix for R seems big, I hope you don't run out of memory.

4
  • 10
    this one liner should do this too outer(1:4, 1:4, pmin)
    – dickoa
    Commented Jul 9, 2013 at 17:48
  • @dickoa: I was concerned that pmin would be called more than once, but no. So yes, that's another good suggestion.
    – flodel
    Commented Jul 9, 2013 at 17:50
  • 3
    also, pmax.int() may be faster still if you are working with just integers.
    – Seth
    Commented Jul 9, 2013 at 18:24
  • Here's another ugly, cryptic, slow one :) chol2inv(chol(matrix(c(rep(c(2,-1,rep(0,N-2),-1),N-1),1),N,N)))
    – cryo111
    Commented Jul 10, 2013 at 3:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.