Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: How to convert matrix to variables in MATA


From   [email protected] (William Gould, Stata)
To   [email protected]
Subject   Re: st: How to convert matrix to variables in MATA
Date   Tue, 12 Dec 2006 08:29:38 -0600

Bamidele Tayo <[email protected]> goes through some Mata macinations, 


        : D1 = st_data((1,6),"wt")
        : D2 =invvech(D1)
        : D3 =vec(D2)

and then wants to save D3 as "an ASCII or Stata file".

I have a solution, but I wish Bamidele had been more specific.  Here's 
what I'm wondering:

     1.  Does Bamidele prefer ASCII or Stata?

     2.  Is Bamidele using the term "Stata" generically, or does he really
         mean a Stata .dta file, or is he just looking for some easy way 
         to restore D3 to Mata later?

I'm going to assume the answer to (1) is "Stata" and the answer to (2)
is that "Stata" is being used generically.  In that case, the easy 
thing to do is 

        : mata matsave myfile D3
        (saving D3[9,1])
        file myfile.mmat saved

Later, when Bamidele wants D3 back, he can type 

        : mata matuse myfile
        (loading D3[9,1])

myfile.mmat is a Mata Matrix file.  Bamidele can learn more about .mmat files
by typing -help mata matsave-.

Alternatively, perhaps Bamidele really meant the ASCII part.  In that case, 
the following would work:

        : fh = fopen("myfile.raw", "w")

        : for (i=1; i<=rows(D3); i++) {
        >         fput(fh, sprintf("%20.0g", D3[i]))
        > }
 
        : fclose(fh)

Reading it back is a bit more tedious, obviously.

Even easier would be, 

        : fh = fopen("myfile.bin", "w")

        : fputmatrix(fh, D3)

        : fclose(fh)

but that would *NOT* be an ASCII file.  The Mata function fputmatrix()
writes the Matrix in a compact, binary format.  It's awfully easy to 
read back, however:

        : fh = fopen("myfile.bin", "r")

        : D3 = fgetmatrix(fh)

        : fclose(fh)

All of this is covered in -help mata fopen()-.

-- Bill
[email protected]
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index