Announcement

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

  • From Stata matrix to code to generate said matrix

    Hi All

    I have a Stata matrix that I want to use as an example for a separate post on Statalist. It would be nice to have the code that generates the matrix as the matrix isnt too large and I could just paste the code straight into the question. For example if I have the matrix x, I want a function that will return the matrix define code to generate said matrix. I imagine this is not too complicated.

    For example, here is a matrix x which is in Stata's memory:
    Click image for larger version

Name:	Untitled.png
Views:	1
Size:	971 Bytes
ID:	1684386




    I want to run a command or block of code that returns to the screen (prints out):
    matrix def x=1,2\3,4

    Any ideas?

  • #2
    Perhaps this.
    Code:
    matrix def x=1,2\3,4
    matrix list x
    local nr = rowsof(x)
    local nc = colsof(x)
    forvalues r = 1/`nr' {
        forvalues c = 1/`nc' {
            local cell = x[`r',`c']
            local m `m'`cell'
            if `c'!=`nc' local m `m',
        }
        if `r'!=`nr' local m `m'\\
    }
    display `"matrix def x=`m'"'
    Code:
    . display `"matrix def x=`m'"'
    matrix def x=1,2\3,4

    Comment


    • #3
      In case the matrix has interesting row and/or column names:

      Code:
      matrix x = 1,2\3,4
      matrix rownames x = good great
      matrix colnames x = first:one last:one
      
      matrix list x
      local nr = rowsof(x)
      local nc = colsof(x)
      local rn: rowfullnames x
      local cn: colfullnames x
      
      forvalues r = 1/`nr' {
          forvalues c = 1/`nc' {
              local cell = x[`r',`c']
              local m `m'`cell'
              if `c'!=`nc' local m `m',
          }
          if `r'!=`nr' local m `m'\\
      }
      
      display `"matrix def x = `m'"'
      display `"matrix rownames x = `rn'"'
      display `"matrix colnames x = `cn'"'
      Last edited by Hemanshu Kumar; 05 Oct 2022, 08:48.

      Comment


      • #4
        Thanks guys.

        I have learned quite a bit from looking at both of your helpful suggestions and I have used them.

        Now on to my original query!

        Regards,
        Bruce

        Comment

        Working...
        X