如何用r中任何数据类型的信号采样向量的移位版本创建矩阵?

时间:2019-05-07 19:43:50

标签: r

我已经问过这个问题,并且在这里how to create the matrix with the shifted version of signal samaples vector in r?得到了必需的答案。 但是在那上面写的函数(可接受的ans)不适用于输入向量的浮点值。因此,我发现了以下补救措施

library("pracma")

v=seq(1,5.5,by=0.5)
step=2
N <- pracma::numel(v)
index <- seq(N,1,by=-step)
index1<- seq(1,(N+step))
M <- pracma::numel(index)
val=matrix(0,(N+step),M)
for ( i in 1:M)
{
for (j in index1)
 {
     if(j<=index[i])
     { 
      val[j,i] =1
     }

  }
 }

value=matrix(repmat(c(v,integer(step)),1,M),(N+step),M)*val
out=matrix(value[1:(N*M)],N,M)

导致

> out
     [,1] [,2] [,3] [,4] [,5]
 [1,]  1.0  0.0  0.0  0.0  0.0
 [2,]  1.5  0.0  0.0  0.0  0.0
 [3,]  2.0  1.0  0.0  0.0  0.0
 [4,]  2.5  1.5  0.0  0.0  0.0
 [5,]  3.0  2.0  1.0  0.0  0.0
 [6,]  3.5  2.5  1.5  0.0  0.0
 [7,]  4.0  3.0  2.0  1.0  0.0
 [8,]  4.5  3.5  2.5  1.5  0.0
 [9,]  5.0  4.0  3.0  2.0  1.0
[10,]  5.5  4.5  3.5  2.5  1.5
  

对于step = 3

> out
     [,1] [,2] [,3] [,4]
 [1,]  1.0  0.0  0.0    0
 [2,]  1.5  0.0  0.0    0
 [3,]  2.0  0.0  0.0    0
 [4,]  2.5  1.0  0.0    0
 [5,]  3.0  1.5  0.0    0
 [6,]  3.5  2.0  0.0    0
 [7,]  4.0  2.5  1.0    0
 [8,]  4.5  3.0  1.5    0
 [9,]  5.0  3.5  2.0    0
[10,]  5.5  4.0  2.5    1

是否可以通过删除for循环并使其成为紧凑函数来进一步优化代码?

0 个答案:

没有答案