Reputation: 180
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.
Upvotes: 3
Views: 464
Reputation: 89057
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.
Upvotes: 13