Announcement

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

  • Print out matrix values in the process of Mata function

    Hello all,

    I was trying to print out intermediate matrix results in order to debug my Mata function. But I failed to find an appropriate built-in function. It seems that printf() can only print out scalar values. Is there another function to use? If not, how would you usually debug your codes in Mata?

    Thank you in advance!

  • #2
    At the point in you code (inside the function you're creating) where you want the matrix to be displayed, write the name of the matrix to the far left side of your text editor. An example is shown below with a matrix named M inside a function.
    Code:
    void function showMatrix(real matrix M) {
        
        printf("\nI'm going to display a matrix for debugging purposes\n")
    // Start displaying
    M
    // End displaying
    
        printf("I've shown you how\n")
    }
    It's illustrated below in a use case where I call the Mata function from within Stata.

    .ÿ
    .ÿversionÿ16.1

    .ÿ
    .ÿclearÿ*

    .ÿ
    .ÿlocalÿline_sizeÿ`c(linesize)'

    .ÿsetÿlinesizeÿ79

    .ÿ
    .ÿmata:
    -------------------------------------------------ÿmataÿ(typeÿendÿtoÿexit)ÿ-----
    :ÿmataÿsetÿmatastrictÿon

    :ÿ
    :ÿvoidÿfunctionÿshowMatrix(realÿmatrixÿM)ÿ{
    >ÿÿÿÿÿ
    >ÿÿÿÿÿÿÿÿÿprintf("\nI'mÿgoingÿtoÿdisplayÿaÿmatrixÿforÿdebuggingÿpurposes\n")
    >ÿ//ÿStartÿdisplaying
    >ÿM
    >ÿ//ÿEndÿdisplaying
    >ÿ
    >ÿÿÿÿÿÿÿÿÿprintf("I'veÿshownÿyouÿhow\n")
    >ÿ}

    :ÿ
    :ÿend
    -------------------------------------------------------------------------------

    .ÿ
    .ÿsetÿlinesizeÿ`line_size'

    .ÿ
    .ÿ*
    .ÿ*ÿDemonstration
    .ÿ*
    .ÿ
    .ÿtempnameÿMyMatrixÿ

    .ÿmatrixÿinputÿ`MyMatrix'ÿ=ÿ(1ÿ2ÿ3ÿ\ÿ4ÿ5ÿ6ÿ\ÿ7ÿ8ÿ9)

    .ÿ
    .ÿmata:showMatrix(st_matrix("`MyMatrix'"))

    I'mÿgoingÿtoÿdisplayÿaÿmatrixÿforÿdebuggingÿpurposes
    ÿÿÿÿÿÿÿ1ÿÿÿ2ÿÿÿ3
    ÿÿÿÿ+-------------+
    ÿÿ1ÿ|ÿÿ1ÿÿÿ2ÿÿÿ3ÿÿ|
    ÿÿ2ÿ|ÿÿ4ÿÿÿ5ÿÿÿ6ÿÿ|
    ÿÿ3ÿ|ÿÿ7ÿÿÿ8ÿÿÿ9ÿÿ|
    ÿÿÿÿ+-------------+
    I'veÿshownÿyouÿhow

    .ÿ
    .ÿ
    .ÿexit

    endÿofÿdo-file


    .

    Comment

    Working...
    X