Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Populating empty matrix conditional on elements of another matrix with for loop.

    Hi!

    I'm new to mata and I'm trying to populate elements of an empty matrix (depending whether they are diagonal elements or not) conditional on values of another matrix.

    The way I coded this is:

    W=(1,2\1,2\2,2)

    R=J(3,3,0)

    for (i=1; i<=rows(R); i++) {

    for (j=1; j<=cols(R); j++) {

    for (k=1; k<=rows(W); k++) {

    if (i==j && W[k,1]==W[k,2])

    R[i,j]=W[k,1]+W[k,2]

    else if (i==j && W[k,1]!=W[k,2])

    R[i,j]=1

    else

    R[i,j]=0

    }
    }
    }

    I've attached the output matrix R, which shows that it doesn't work. Can anyone explain why this is the case?

    Kind regards,

    Ulrich
    Attached Files

  • #2
    I don't know why you want to do that, but in this particular case you can avoid the loop, which is always a good idea. Loops in Mata are slow so it's to best to vectorize your code whenever possible. It is especially true, when you matrices tend to be big.
    If you are new to Mata I will recommend that you learn about the colon operator (and r-comformabilty) for elementwise operations.

    Code:
    d = W[,1]:==W[,2]
    s = d:*rowsum(W) + (1:-d)
    R = diag(s)
    Hope it helps

    Comment

    Working...
    X