Search code examples
rmatrix

Create an off diagonal / moving window matrix


How to create an off diagonal / moving window matrix with R?

> offdiag(3, 4, 6)

1 1 1 0 0 0
0 1 1 1 0 0
0 0 1 1 1 0
0 0 0 1 1 1 

Solution

  • I suggest creating a sparse logical matrix:

    library(Matrix)
    X <- bandSparse(n = 4, m = 6, k = seq_len(3) - 1L)
    X
    #4 x 6 sparse Matrix of class "ngCMatrix"
    #
    #[1,] | | | . . .
    #[2,] . | | | . .
    #[3,] . . | | | .
    #[4,] . . . | | |
    

    If you need a dense integer matrix:

    +as.matrix(X)
    #     [,1] [,2] [,3] [,4] [,5] [,6]
    #[1,]    1    1    1    0    0    0
    #[2,]    0    1    1    1    0    0
    #[3,]    0    0    1    1    1    0
    #[4,]    0    0    0    1    1    1