Announcement

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

  • Block diagonal matrix in Stata

    Is there a way to generate a block diagonal matrix in Stata (no mata, if possible) starting from 2 matrices, such that the resulting matrix preserves the equation and column/row names of the original matrices? I can certainly write my program to do that, but maybe there's a quicker solution I'm not aware of.

  • #2
    There is no matrix function to do this directly, i.e you will have to write more than one line of code. Mata has a blockdiag() function and you could you use 3 lines of codes to achieve what you want

    Code:
    mat A = J(2,2,1)
    mat B = J(2,2,2)
    local aname a1 a2
    mat coln A = `aname'
    mat rown A = `aname'
    
    local bname b1 b2
    mat coln B = `bname'
    mat rown B = `bname'
    
    mat li A
    mat li B
    
    // (minimal) Mata way
    mata: st_matrix("M",blockdiag(st_matrix("A"),st_matrix("B")))
    
    
    // or Stata way
    local r = `=rowsof(A)' + `=rowsof(B)'
    local c = `=colsof(A)' + `=colsof(B)'
    mat M = J(`r',`c',0)
    mat M[1,1] = A
    mat M[`=rowsof(A)+1',`=colsof(A)+1'] = B
    mat li M
    
    mat coln M = `: coln A' `: coln B'
    mat rown M = `: rown A' `: rown B'
    mat li M

    Comment


    • #3
      Thank you very much, Christophe. I'm glad to see that my code looks very similar to yours
      Last edited by Andrea Discacciati; 30 Nov 2016, 09:27.

      Comment

      Working...
      X