Select from Matrix

  • Lukas Stötzer

    Lukas Stötzer - 2013-03-12

    Dear all,

    I would like to select entries from a matrix for which a certain condition holds true. I am puzzled how I can implement this in JAGS.

    In my specific application, I would like to sample the sensitivity of a copy-detection test. Say, beta[i,j] is a matrix that estimates if a individual i copied on item j from his neighbor (copied 1; not copied 0). The matrix copied[i,j] shows the true copy behavior, if copied[i,j] is 1 a person copied ; and 0 if not. In order to get the sensitivity of the estimate, I would first like to see if beta[i,j] equals copied[i,j] - the correctly predicted cases CP[i,j] and than select all values from from this where copied[i,j]==1.

    This is how I would select entries in R:

    beta <- matrix(1:9,3,3)
    copied <- matrix(0,3,3)
    copied[2,1] <- 1
    CP[i,j] <- as.numeric(beta == copied)

    I tried the same CP[copied==1] in JAGS but it doesn't seem to work. Is there any other way to select entries from this matrix? This is how far I got:

    model {
    for (i in 1:N){
        for(j in 1:J){
            # Copy model (simplfied version)
            beta[i,j] ~ dbern(p)
            # Coorectly Predicted Cases
            CP[i,j] <-   equals(beta[i,j],copied[i,j])
    sens <- CP[copied==1]
    # Prior for probaility that copied
    p ~ dbeta(1,10)

    Thank you for any help on this! Kind regards,
    Lukas Stötzer

  • Martyn Plummer

    Martyn Plummer - 2013-03-13

    The BUGS language looks similar to R, but is not vectorized and does not have logical subsetting.

    Instead of having an indicator matrix with entries 0 or 1. You can use a vectors row and col giving the rows and corresponding columns of the non-zero entries of the matrix copied. Suppose there are nz non-zero entries, then you create sens with;

    for (i in 1:nz) {
       sens[i] <- CP[row[i], col[i]]
  • Lukas Stötzer

    Lukas Stötzer - 2013-03-25

    That works. Thank you!


Log in to post a comment.