简体   繁体   中英

Is there a way to replicate a matrix with overlapping pattern?

I am trying to create a matrix which will replicate according to user input. eg

1 0 0 0
1 0 0 0
1 1 0 0
0 1 0 0
0 1 1 0
0 0 1 0
0 0 1 1
0 0 0 1
1 0 0 1
1 0 0 0
1 1 0 0
.......
.......

We can see that after filling in 3 rows,new column starts to follow the same pattern. Here the number of rows should be dynamic.

#Input
n_col = 4
n_row = 15
offset_row = 3
basic_pattern = c(1, 1, 1, 0, 0, 0, 0, 0)
#End Input

do.call(cbind,
        lapply(1:n_col, function(j){
            n_zero_top = (j - 1) * (offset_row - 1)
            c(rep(x = 0, times = n_zero_top),
              rep(x = basic_pattern, length.out = n_row - n_zero_top))
        }))
#      [,1] [,2] [,3] [,4]
# [1,]    1    0    0    0
# [2,]    1    0    0    0
# [3,]    1    1    0    0
# [4,]    0    1    0    0
# [5,]    0    1    1    0
# [6,]    0    0    1    0
# [7,]    0    0    1    1
# [8,]    0    0    0    1
# [9,]    1    0    0    1
#[10,]    1    0    0    0
#[11,]    1    1    0    0
#[12,]    0    1    0    0
#[13,]    0    1    1    0
#[14,]    0    0    1    0
#[15,]    0    0    1    1

Maybe the following could also work for basic_pattern

ones = c(1, 1, 1)
#basic_pattern = c(1, 1, 1, 0, 0, 0, 0, 0)
basic_pattern = c(ones, rep(x = 0, times = (offset_row - 1) * n_col - length(ones)))

Another dynamic approach would be

# define pattern
pattern <- c(1,1,1,0,0,0,0,0)

# number of rows and cols
nrows <- 20
ncols <- 4

# choose rownumber where pattern repeats
rownum <- 3


# Generating data
m <- matrix(c(pattern, rep(0, nrows*ncols - length(pattern))), ncol= ncols)
# identify the length of the pattern
patternlength <- length(pattern)
# repeat pattern in column 1 as desired
m[, 1] <- rep(m[1:patternlength, 1], ceiling(nrow(m)/patternlength))[1:nrow(m)]
# repeat pattern in other columns
sapply(2:ncol(m), function(x){ 
m[rownum:nrow(m), x] <<- m[1:(nrow(m)-rownum + 1), x-1]})
# see results
m
#       [,1] [,2] [,3] [,4]
# [1,]    1    0    0    0
# [2,]    1    0    0    0
# [3,]    1    1    0    0
# [4,]    0    1    0    0
# [5,]    0    1    1    0
# [6,]    0    0    1    0
# [7,]    0    0    1    1
# [8,]    0    0    0    1
# [9,]    1    0    0    1
#[10,]    1    0    0    0
#[11,]    1    1    0    0
#[12,]    0    1    0    0
#[13,]    0    1    1    0
#[14,]    0    0    1    0
#[15,]    0    0    1    1
#[16,]    0    0    0    1
#[17,]    1    0    0    1
#[18,]    1    0    0    0
#[19,]    1    1    0    0
#[20,]    0    1    0    0

EDIT:

I added the variables pattern, nrows and ncols to show that this approach is dynamic, too.

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