Statalist The Stata Listserver


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

Re: st: mata st_view( ) and change in stata data


From   [email protected] (William Gould, Stata)
To   [email protected]
Subject   Re: st: mata st_view( ) and change in stata data
Date   Thu, 30 Nov 2006 07:49:27 -0600

Carl Nelson <[email protected]> notes

> The mata manual explains
> 
>   : st_view(X, ., ("mpg", "displ", "weight"))
>   : X[2,1] = 123
> 
> will cause the second observation of mpg in stata to change.

and Carl then tries to apply that, 

>    : st_view(a, ., ("over04", "over05", ...))
>    : t = (0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\70\0\0\0\0\0\0\0\0\0\0\0\0\0)
>    : a = a :+ t

but, 

> After I run this the matrix a in mata is correct, but the variables 
> in the stata data set haven't been changed.

Solution:  change 

     : a = a :+ t

to read 

     : a[.,.] = a :+ t

By the way, easier tyan typing 

     : t = (0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\70\0\0\0\0\0\0\0\0\0\0\0\0\0)

is

      : t = J(rows(a), 1, 0)


Explanation
-----------

You need to type

                a[.,.] = a :+ t

rather than 

                a = a :+ t

because you want Mata to replace the elements of existing matrix a, 
not redefine a.  That's a subtle difference, but important.  When you
type 

                a = a :+ t

Mata calculates -a :+ t-, throws away the current a, and redefines a to 
be the calculated result.  It's important that Mata works that way.
Pretend you code, 

                a = (1, 2 \ 3, 4)
                ...
                a = (1, 2, 3 \ 4, 5, 6)

That is, early on, you define a to be 2x2, and later, you redefine it to 
be 3x3.  If Mata simply tried to reassign the elements of the current a, 
the second statement would be an error, because a 3x3 will not fit into a 
2x2.

The little example I just gave is no different conceptually than what 
Carl coded, 

                st_view(a, ., ("over04", "over05", ...))
                ...
                a = a :+ t

The first line provided one definition of a, and the third, another, new 
definition.  

What Carl wanted to do, however, was maintain the current definition of 
a and replace its (already existing) elements.  Just as you replace the 
2, 1 element of X by coding 

                X[2,1] = 123

you replace all the elements of a by coding 

                a[.,.] = ...


-- 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