Announcement

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

  • Extract elements of matrix

    I am writing code which performs a matrix calculation, generates a matrix result A, and then I want to put the elements of A into variables (or scalars, or locals).

    To illustrate, the matrix A = [2 5 6], and has column names A1 A2 A3. The issue is that I am unable to use column names to extract the desired elements, as the following illustrates:

    . mat list A

    A[1,3]
    A1 A2 A3
    r1 2 5 6

    . di A[1,2]
    5

    . di A[1,A2]
    A2 not found
    r(111);

    . di A[1,"A2"]
    matrix operators that return matrices not allowed in this context
    r(509);

    What am I doing wrong?

  • #2
    What version of Stata do you have? In Stata 16, the following is possible:

    Code:
    mat A = [2,5,6]
    mat colnames A = "A1" "A2" "A3"
    di A[1,"A2"]
    Res.:

    Code:
    . mat A = [2,5,6]
    
    . 
    . mat colnames A = "A1" "A2" "A3"
    
    . 
    . di A[1,"A2"]
    5

    Comment


    • #3
      Thanks for the response, Andrew. Your code is exactly what I'm trying to get working. I'm using version 14.2, from 2018, and it hadn't occurred to me that such a basic bit of syntax would be a new innovation.

      Comment


      • #4
        Back then you needed the rownumb() and colnumb() functions to explicitly refer to the row name and column name, respectively. Something like:

        Code:
        mat A = [2,5,6]
        mat colnames A = "A1" "A2" "A3"
        di A[1,colnumb(A, "A2")]
        Res.:

        Code:
        . mat A = [2,5,6]
        
        . 
        . mat colnames A = "A1" "A2" "A3"
        
        . 
        . di A[1,colnumb(A, "A2")]
        5

        Comment


        • #5

          you're my savior Andrew, thanks! I try to avoid shelling out for every new version of Stata (I've been using it since version 1.3 in the late 1980s), but I guess might have to pony up for v16.

          Comment

          Working...
          X