简体   繁体   中英

Create a certain matrix in R

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM