有没有办法复制具有重叠模式的矩阵?

时间:2019-03-31 13:44:04

标签: r matrix

我正在尝试创建一个矩阵,该矩阵将根据用户输入进行复制。 例如

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
.......
.......

我们可以看到,在填充3行之后,新列开始遵循相同的模式。 这里的行数应该是动态的。

2 个答案:

答案 0 :(得分:0)

#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

也许以下情况也可能适用于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)))

答案 1 :(得分:0)

另一种动态方法是

# 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

编辑:

我添加了变量模式,nrows和ncols,以表明该方法也是动态的。