Announcement

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

  • format a matrix

    Hello user,

    For example, I have a matrix A = (1.12132, 3.036563, 3.2323 \ 2.60223, 3.710003, 4.5343342 ).

    How could I format the matrix A round every element with 2 decimal) as follows:
    A = (1.12, 3.04, 3.23 \ 2.60, 3.71, 4.53 ).

    Thanks a lot in advance.

  • #2
    Formatting a matrix is a matter of display only; stored values are not affected.

    If you want a record of that matrix with just 2 decimal places, that is a string conversion and best accomplished in Mata.

    Rounding numerically to 2 decimal places could at best be an approximation given precision issues.

    Code:
    .  matrix A = (1.12132, 3.036563, 3.2323 \ 2.60223, 3.710003, 4.5343342 )
    
    . mat li A, format(%3.2f)
    
    A[2,3]
          c1    c2    c3
    r1  1.12  3.04  3.23
    r2  2.60  3.71  4.53
    
    . mata
    ------------------------------------------------- mata (type end to exit) ------
    : A = st_matrix("A")
    
    : strofreal(A, "%3.2f")
              1      2      3
        +----------------------+
      1 |  1.12   3.04   3.23  |
      2 |  2.60   3.71   4.53  |
        +----------------------+

    Comment


    • #3
      Dear Cox,

      I used your mata code in an attempt to round the matrix A to 2 decimal. However, it seems that the matrix A is unchanged.

      Could you provide the mata code for this purpose?

      Comment


      • #4
        (My first name is Nick; Cox is the family name; using the first is conventional here, please, if you wish to use names at all.)

        My Mata code doesn't purport to change the matrix. It just shows a string representation in Mata.

        You should follow entries in

        Code:
         
        search precision
        to see that the desire here is problematic. But as you press the point, this is a way to give you what I think you think you want.

        Code:
        . matrix A = (1.12132, 3.036563, 3.2323 \ 2.60223, 3.710003, 4.5343342 )
        
        . matmap A B, map(round(@, 0.01))
        
        . mat li B
        
        B[2,3]
              c1    c2    c3
        r1  1.12  3.04  3.23
        r2   2.6  3.71  4.53
        
        . mat li B, format(%21.18f)
        
        B[2,3]
                              c1                    c2                    c3
        r1  1.120000000000000100  3.040000000000000000  3.230000000000000000
        r2  2.600000000000000100  3.710000000000000000  4.530000000000000200
        Here matmap is from SSC. Note that the last example underlines that you can only ever get 2 decimal places as an approximation.

        Comment


        • #5
          And if you don't want to change the matrix, and just want to display it to 2 decimal places:

          Code:
          matrix list A, format(%3.2f)

          Comment

          Working...
          X