gpt4 book ai didi

r - 一种更快(矢量化)的方法来创建具有预定长度的1和0的滑动序列

转载 作者:行者123 更新时间:2023-12-04 13:45:57 25 4
gpt4 key购买 nike

我有以下有效的功能,但我觉得有一种更快的方式(矢量化的还是包装的或内置的?)来编写此功能?

create_seq <- function(n, len) {
mat <- matrix(nrow = length(0:(n-len)), ncol = n)
for(i in 0:(n-len)) {
mat[i + 1, ] <- c(rep(0L, i), rep(1L, len), rep(0L, n - (len + i)))
}
return(mat)
}

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

最佳答案

创建一个稀疏的带状矩阵:

library(Matrix)    

create_seq_sparse <- function(n, len) {
bandSparse(m = n, n = n - len + 1L, k = seq_len(len) - 1L)
}

create_seq_sparse(10, 3)
# 8 x 10 sparse Matrix of class "ngCMatrix"
#
# [1,] | | | . . . . . . .
# [2,] . | | | . . . . . .
# [3,] . . | | | . . . . .
# [4,] . . . | | | . . . .
# [5,] . . . . | | | . . .
# [6,] . . . . . | | | . .
# [7,] . . . . . . | | | .
# [8,] . . . . . . . | | |

create_seq_sparse(7, 2)
#6 x 7 sparse Matrix of class "ngCMatrix"
#
#[1,] | | . . . . .
#[2,] . | | . . . .
#[3,] . . | | . . .
#[4,] . . . | | . .
#[5,] . . . . | | .
#[6,] . . . . . | |

如果需要密集的数字矩阵,则可以使用 +as.matrix(...)作为最后一步。

关于r - 一种更快(矢量化)的方法来创建具有预定长度的1和0的滑动序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54330047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com