简体   繁体   中英

Create the matrix with a repeating pattern (R)

There should be a matrix created without a vector. Like a simplified one without entering all the data in the vector.

matrix(c(0, 1, 2, 0, 1, 1, 2, 0, 1, 2, 2, 0, 1, 2, 0, 0, 1, 2, 0, 1, 1, 2, 0, 1, 2), nrow = 5, ncol = 5) 

I've tried:

matrix(0:2, ncol=5, nrow=5)
 > matrix

      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    2    1    0    2
 [2,]    1    0    2    1    0
 [3,]    2    1    0    2    1
 [4,]    0    2    1    0    2
 [5,]    1    0    2    1    0

But it's not helping, as each column should start with the number the previous column ends with.

The final matrix should look like:

> matrix
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    0    1
 [2,]    1    2    0    1    2
 [3,]    2    0    1    2    0
 [4,]    0    1    2    0    1
 [5,]    1    2    0    1    2

You can use the index numbers of the rows and columns, and combine the value with the modulo operator %% like this:

n = 5
mat <- matrix(nrow = n, ncol = n)
mat <- (row(mat) + col(mat) + 1) %% 3

> mat
      [,1] [,2] [,3] [,4] [,5] 
[1,]    0    1    2    0    1
[2,]    1    2    0    1    2
[3,]    2    0    1    2    0
[4,]    0    1    2    0    1
[5,]    1    2    0    1    2

mat <- matrix(0:2, nrow = 7, ncol = 5)

> mat
    [,1] [,2] [,3] [,4] [,5]
[1,]    0    1    2    0    1
[2,]    1    2    0    1    2
[3,]    2    0    1    2    0
[4,]    0    1    2    0    1
[5,]    1    2    0    1    2
[6,]    2    0    1    2    0
[7,]    0    1    2    0    1

mat2 <- mat[-6:-7, ]

> mat2
      [,1] [,2] [,3] [,4] [,5]
 [1,]    0    1    2    0    1
 [2,]    1    2    0    1    2
 [3,]    2    0    1    2    0
 [4,]    0    1    2    0    1
 [5,]    1    2    0    1    2

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