Announcement

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

  • row / col concatenation when of differeng lengths

    this is probably completely obvious, but suppose I want a 3x2 matrix with all "1"s in the 1st column and numbers like 2,3,4 in the second column. I thought I could just type (1,(2 \ 3\ 4)), but that throws a conformability error, I could do this using the J() function for the first column, but because we do this kind of thing all the time, I thought there might be a much quicker way. is there? - P

  • #2
    Originally posted by Paul Rathouz View Post
    . . . I want a 3x2 matrix with all "1"s in the 1st column and numbers like 2,3,4 in the second column.
    Maybe
    Code:
    mata
    diagonal(I(3)), (2::4)
    :ÿdiagonal(I(3)),ÿ(2::4)
    ÿÿÿÿÿÿÿ1ÿÿÿ2
    ÿÿÿÿ+---------+
    ÿÿ1ÿ|ÿÿ1ÿÿÿ2ÿÿ|
    ÿÿ2ÿ|ÿÿ1ÿÿÿ3ÿÿ|
    ÿÿ3ÿ|ÿÿ1ÿÿÿ4ÿÿ|
    ÿÿÿÿ+---------+

    :

    Comment


    • #3
      Paul, for what it's worth I've come to increasingly appreciate the flexibility of J(., ., .) in Mata programming. Among other things the fact that its third argument can be a vector or matrix has sometimes streamlined otherwise messy programming.

      Code:
      mata
      
      r1=J(3,1,1)
      r2=J(1,1,J(3,1,1))
      
      r1
      r2
      
      end
      This yields
      Code:
      : r1=J(3,1,1)
      
      : r2=J(1,1,J(3,1,1))
      
      :
      : r1
             1
          +-----+
        1 |  1  |
        2 |  1  |
        3 |  1  |
          +-----+
      
      : r2
             1
          +-----+
        1 |  1  |
        2 |  1  |
        3 |  1  |
          +-----+

      Comment


      • #4
        Originally posted by Paul Rathouz View Post
        . . . because we do this kind of thing all the time, I thought there might be a much quicker way.
        I forgot to mention that if you don't want to type all that out each time, then you can just park it all into a convenient custom function.
        Code:
        mata:
        
        real matrix function oar(real scalar rows) return(J(rows, 1, 1), (2::rows+1))
        
        // or
        
        real matrix function dar(real scalar rows) return(diagonal(I(rows)), (2::rows+1))
        
        oar(3)
        dar(3)
        
        end
        
        exit

        Comment

        Working...
        X