I encountered a very strange behavior when I use Mata views on temporary variables created by fvrevar. I tried to keep the following example as simple as possible:
The two Mata matrices displayed by running this code should be identical but they are not:
I do not understand why the second matrix is full of zeros. This does not make any sense to me. Does anybody have an idea where I am going wrong? Or is this indeed some weird bug?
I get the same results in all versions from Stata 12 until the most recent update of Stata 16.
Code:
clear all
webuse hsng2
mata:
void mydemean(string scalar varlist, string scalar newvars, string scalar touse) {
real matrix X, Xn
st_view(X, ., varlist, touse)
st_view(Xn, ., newvars, touse)
Xn[., .] = X :- mean(X)
X :- mean(X)
Xn
}
end
tempvar touse
gen byte `touse' = 0
replace `touse' = 1 in 34/37
loc varlist "1b.region 2.region 3.region 4.region"
foreach var in `varlist' {
fvrevar `var'
loc var "`r(varlist)'"
qui replace `var' = .
loc newvars "`newvars' `var'"
}
mata: mydemean("`varlist'", "`newvars'", "`touse'")
Code:
1 2 3 4
+-----------------------------+
1 | 0 -.25 -.25 -.25 |
2 | 0 .75 -.25 -.25 |
3 | 0 -.25 .75 -.25 |
4 | 0 -.25 -.25 .75 |
+-----------------------------+
[symmetric]
1 2 3 4
+-----------------+
1 | 0 |
2 | 0 0 |
3 | 0 0 0 |
4 | 0 0 0 0 |
+-----------------+
I get the same results in all versions from Stata 12 until the most recent update of Stata 16.

Comment