如何在r中的信号samaples向量的偏移版本中创建矩阵?

时间:2019-05-01 18:59:31

标签: r

这个问题我已经问过Matlab了,我得到了所需的答案。这是该问题的链接-how to create the matrix with the shifted version of the signal samples in Matlab?。 当我在Matlab和r中处理数据时,我正在尝试为r开发相同的代码。在这种尝试中,我使用给定(尚未接受)的答案向给定链接How to form the matrix of logical '1' and '0' using two vectors and logical operators in r?询问以下问题:第二个问题是我开发了以下r代码。

library("pracma")
x=c(1:10)
N=numel(x)
step=2
index=seq(N,1,by=-step)
M=numel(index)
r1 <- c(rbind((index), rev(index)))
val<-matrix(rep(rep(c(1, 0), M), r1), ncol = M)
val1=val*matrix(repmat(c(x,matrix(0,1,step)),1,M),12,M)
out=matrix(val1[1:(N*M)],N,M)

这将导致

 > out
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    0    0
[2,]    2    0    0    0    0
[3,]    3    1    0    0    0
[4,]    4    2    0    0    0
[5,]    5    3    1    0    0
[6,]    6    4    2    0    0
[7,]    7    5    3    1    0
[8,]    8    6    4    2    0
[9,]    9    7    5    3    1
[10,]   10    8    6    4    2

但是当我更改步长将无法使用时,如何使此代码更笼统地体现步长?

1 个答案:

答案 0 :(得分:1)

如@NelsonGon在评论中所述,创建一个对代码稍加修改的函数会有所帮助

f1 <- function(v, step) {

    N <- pracma::numel(v)
    index <- seq(N,1,by=-step)
    M <- pracma::numel(index)
    r1 <- c(rbind((index), rev(index)))
    val <- matrix(rep(rep(c(1, 0), M), r1), ncol = M)
    val[!!val] <- sequence(colSums(val))
    apply(val[x,], 2, function(x) x[order(x != 0)])
}

-测试

f1(1:10, 2)
#       [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0    0    0    0
# [2,]    2    0    0    0    0
# [3,]    3    1    0    0    0
# [4,]    4    2    0    0    0
# [5,]    5    3    1    0    0
# [6,]    6    4    2    0    0
# [7,]    7    5    3    1    0
# [8,]    8    6    4    2    0
# [9,]    9    7    5    3    1
#[10,]   10    8    6    4    2

f1(1:10, 3)
#      [,1] [,2] [,3] [,4]
# [1,]    1    0    0    0
# [2,]    2    0    0    0
# [3,]    3    0    0    0
# [4,]    4    1    0    0
# [5,]    5    2    0    0
# [6,]    6    3    0    0
# [7,]    7    4    1    0
# [8,]    8    5    2    0
# [9,]    9    6    3    0
#[10,]   10    7    4    1

注意:如果打算将列也只保留0,则可以在函数中完成

f1(1:10, 4)
#        [,1] [,2] [,3]
# [1,]    1    0    0
# [2,]    2    0    0
# [3,]    3    0    0
# [4,]    4    0    0
# [5,]    5    1    0
# [6,]    6    2    0
# [7,]    7    3    0
# [8,]    8    4    0
# [9,]    9    5    1
#[10,]   10    6    2

f1(1:10, 5)
#      [,1] [,2]
# [1,]    1    0
# [2,]    2    0
# [3,]    3    0
# [4,]    4    0
# [5,]    5    0
# [6,]    6    1
# [7,]    7    2
# [8,]    8    3
# [9,]    9    4
#[10,]   10    5