Hi all. I've run into something puzzling and perhaps of general interest.
Within Mata, I set up a view X to a Stata variable "mpg" (guess which dataset!), and a pointer pX to the view X.
If I change X[1,1] to some value, the first observation in mpg changes to that value. That's how views are supposed to work.
But if I change *pX[1,1] to some value, then even though X[1,1] changes, the underlying Stata variable does NOT change. I can't work out why.
The code below demonstrates (Stata 13.1):
which leads the following output:
When I call the Mata function mymatafn_view(.), X[1,1] changes to 1000, and so does the first ob in the Stata variable mpg.
But when I call the Mata function mymatafn_pointer(.), and *pX[1,1] changes to 2000, even though X[1,1] also changes to 2000, the first ob in mpg stays unchanged at 1000.
Any ideas? This is of practical significance; I have an application where I want to pass around a pointer to a view, and have any changes made be reflected in the underlying Stata variable.
Within Mata, I set up a view X to a Stata variable "mpg" (guess which dataset!), and a pointer pX to the view X.
If I change X[1,1] to some value, the first observation in mpg changes to that value. That's how views are supposed to work.
But if I change *pX[1,1] to some value, then even though X[1,1] changes, the underlying Stata variable does NOT change. I can't work out why.
The code below demonstrates (Stata 13.1):
Code:
mata: mata clear mata: void mymatafn_view(scalar s) { st_view(X, ., "mpg") X[1,1] = s // assign "Value of Mata variable X[1,1]:" X[1,1] // display } end mata: void mymatafn_pointer(scalar s) { st_view(X, ., "mpg") pX = &X // pointer *pX[1,1] = s // assign "Value of Mata variable *pX[1,1]:" *pX[1,1] // display "Value of Mata variable X[1,1]:" X[1,1] // display } end sysuse auto, clear list mpg in 1/1 mata: mymatafn_view(1000) list mpg in 1/1 mata: mymatafn_pointer(2000) list mpg in 1/1
Code:
. sysuse auto, clear (1978 Automobile Data) . . list mpg in 1/1 +-----+ | mpg | |-----| 1. | 22 | +-----+ . . mata: mymatafn_view(1000) Value of Mata variable X[1,1]: 1000 . list mpg in 1/1 +------+ | mpg | |------| 1. | 1000 | +------+ . . mata: mymatafn_pointer(2000) Value of Mata variable *pX[1,1]: 2000 Value of Mata variable X[1,1]: 2000 . list mpg in 1/1 +------+ | mpg | |------| 1. | 1000 | +------+
When I call the Mata function mymatafn_view(.), X[1,1] changes to 1000, and so does the first ob in the Stata variable mpg.
But when I call the Mata function mymatafn_pointer(.), and *pX[1,1] changes to 2000, even though X[1,1] also changes to 2000, the first ob in mpg stays unchanged at 1000.
Any ideas? This is of practical significance; I have an application where I want to pass around a pointer to a view, and have any changes made be reflected in the underlying Stata variable.
Comment