Announcement

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

  • conditional indexing of mata matrix

    Hello,

    I have been struggling to figure out a way to index elements of a mata matrix conditionally. My ultimate goal is as follows:

    Consider two n by k matrices A and B, where B contains only 0s and 1s. I would like to place missing values into A at those indices where B is equal to 0.

    If the goal was to place something other than missing values (for example say we wanted to place the number 23), then something like:

    C = A:*B + J(n,k,23):*(J(n,k,1):-B)

    would do the trick. Unfortunately replacing J(n,k,23) by J(n,k,.) does not work.

    Any ideas on how to accomplish this?

    Regards,

    Max


  • #2
    How about

    Code:
    set seed 12345
    mata:
        n = 5
        k = 3
        A = ceil(10*runiform(n,k))
        B = runiform(n,k) :> .3
        A
        B
        A :/ B
    end
    Here is the output:

    Code:
    :         A
           1   2   3
        +-------------+
      1 |  4   5   7  |
      2 |  6   6   3  |
      3 |  1   7   5  |
      4 |  3   1   1  |
      5 |  5   7   9  |
        +-------------+
    
    :         B
           1   2   3
        +-------------+
      1 |  1   0   0  |
      2 |  0   1   0  |
      3 |  1   1   1  |
      4 |  1   1   1  |
      5 |  0   1   1  |
        +-------------+
    
    :         A :/ B
           1   2   3
        +-------------+
      1 |  4   .   .  |
      2 |  .   6   .  |
      3 |  1   7   5  |
      4 |  3   1   1  |
      5 |  .   7   9  |
        +-------------+

    Comment


    • #3
      Hi Rafal,

      That is great. Using division by zero is perfect here, wish I had thought of it.

      Regards,

      Max

      Comment

      Working...
      X