Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A faster (vectorized) way to create a sliding sequence of 1s and 0s with a predetermined length

I have the following function which works, but I feel like there's a faster (either vectorized or perhaps a package or built-in?) way to write this?

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
like image 969
JasonAizkalns Avatar asked Jan 23 '19 14:01

JasonAizkalns


1 Answers

Create a sparse banded matrix:

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

If you need a dense numeric matrix, you can use +as.matrix(...) as the last step.

like image 108
Roland Avatar answered Sep 29 '22 12:09

Roland