Announcement

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

  • Conditions in Mata

    Hi all, I hope someone can help with this problem. I checked other posts but I'm not sure what I'm doing wrong. My goal is to replace some of the elements of a matrix based on some information from a vector. This is the situation,
    The matrix is,
    1 2 3 4
    +-----------------+
    1 | 0 0 0 0 |
    2 | 1 0 0 1 |
    3 | 1 1 1 1 |
    4 | 0 1 0 0 |
    +-----------------+

    and the vector is,
    1
    +-----+
    1 | 0 |
    2 | 1 |
    3 | 1 |
    4 | 0 |
    +-----+
    So the conditions are, i) if the vector's row is zero checking in the same matrix's row all elements, if one of those elements is not zero I need to change it to be zero. ii) If the vector's row is not zero do nothing to the same matrix's rows.
    In the example above the conditions only will actually change the position [4,2] in the matrix from one to zero. From my attempts to do it I got, i) no change or ii) subscript invalid error.

    Thanks in advance

  • #2
    If I understood correctly, this code should do what you intend. Try next time to post the code you have written,, so we can see what you are doing wrong.

    Code:
    . mata :
    ------------------------------------------------- mata (type end to exit) -------------
    : 
    : M = ( 0,0,0,0\
    > 1,0,0,1\
    > 1,1,1,1\
    > 0,1,0,0)
    
    : 
    : v = (0,1,1,0)'
    
    : 
    : 
    : R = M:*J(1,4,v)
    
    : 
    : M
           1   2   3   4
        +-----------------+
      1 |  0   0   0   0  |
      2 |  1   0   0   1  |
      3 |  1   1   1   1  |
      4 |  0   1   0   0  |
        +-----------------+
    
    : v
           1
        +-----+
      1 |  0  |
      2 |  1  |
      3 |  1  |
      4 |  0  |
        +-----+
    
    : R 
           1   2   3   4
        +-----------------+
      1 |  0   0   0   0  |
      2 |  1   0   0   1  |
      3 |  1   1   1   1  |
      4 |  0   0   0   0  |
        +-----------------+
    
    : 
    : end
    ---------------------------------------------------------------------------------------

    Comment


    • #3
      Thank you Christophe. I'll keep in my your suggestion.

      Comment

      Working...
      X