creating a triangular matrix

后端 未结 4 688
有刺的猬
有刺的猬 2020-12-15 08:04

There must an elegant way to do this but I can\'t figure out so:

Columns are probabilities from 1 to 0 going right

Rows are probabilities from 0 to 1 going d

4条回答
  •  清歌不尽
    2020-12-15 08:39

     mat <- matrix(NA, 10,10)
     mat[row(mat)+col(mat) >=11] <- (row(mat)+col(mat) -11)[row(mat)+col(mat)>=11]/10
     mat
          [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
     [1,]   NA   NA   NA   NA   NA   NA   NA   NA   NA   0.0
     [2,]   NA   NA   NA   NA   NA   NA   NA   NA  0.0   0.1
     [3,]   NA   NA   NA   NA   NA   NA   NA  0.0  0.1   0.2
     [4,]   NA   NA   NA   NA   NA   NA  0.0  0.1  0.2   0.3
     [5,]   NA   NA   NA   NA   NA  0.0  0.1  0.2  0.3   0.4
     [6,]   NA   NA   NA   NA  0.0  0.1  0.2  0.3  0.4   0.5
     [7,]   NA   NA   NA  0.0  0.1  0.2  0.3  0.4  0.5   0.6
     [8,]   NA   NA  0.0  0.1  0.2  0.3  0.4  0.5  0.6   0.7
     [9,]   NA  0.0  0.1  0.2  0.3  0.4  0.5  0.6  0.7   0.8
    [10,]    0  0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8   0.9
    

    I think this will be much faster than a plyr solution and I happen to think it is easier to comprehend. It basically sets up a test for the entries that are in the lower right hand "triangle" and then divides the results of that "test" matrix bu 10. You can look at the test matrix with this code:

    row(mat)+col(mat) -11
    

    Edit: I thought it possible that making the matrix once as sebastian-c illustrated and then doing a single test to do the NA setting might be faster ( with one third the number of calls to row and col) but it appears to be only one third as fast. It looks like the two seq calls take more time than the extra :

    mat <- round(outer(seq(-0.5, 0.5, 0.1), seq(-0.5, 0.5, 0.1), `+`), 1)
    is.na(mat) <- row(mat)+col(mat) <= 11
    mat
    

    I did find another solution based on the little known embed function:

    mat <- embed(seq(-1,1, by=0.1), 11 )[,11:1]
    is.na(mat) <- row(mat)+col(mat) <= 11
    

    Although it is 50% faster than the new solution, it is still slower than the original.

提交回复
热议问题