Oleksandr Shepotylo <[email protected]> wrote,
> I want to write a mata function that will take an existing variable X from
> the loaded dataset, multiply it by matrix W that also exist, and create a
> new stata variable Y=W*X .
Oleksandr provided code,
function spatlag(string scalar index, string scalar windex)
{
X=J(0,0,.)
Y=J(0,0,.)
mata matuse L:\FDI\Out\weights2rd
st_addvar("float", windex)
st_view(Y,., windex)
st_view(X,., index)
Y[.,.]=(I(11)#W)*X
}
The probelm, as others have mentioned, is the -mata matuse- right in the
middle of the program. That is a interpretive/convenience command for
use interactively, not in Mata programs. So let's set about fixing the
problem.
First, let's modify the program so that it receives the matrix W as an
argument. Then we will work on getting matrix W from disk and passing it
our subroutine:
function spatlag_mult(real matrix W,
string scalar index, string scalar windex)
{
(void) st_addvar("float", windex)
st_view(Y,., windex)
st_view(X,., index)
Y[.]=(I(11)#W)*X
}
We now pass in W. Also, I deleted the two lines
X=J(0,0,.)
Y=J(0,0,.)
because they were unnecessary, and I added a -(void)- in front of
-st_addvar()- because it returns the newly created variable's index,
and that would have been displayed.
Now let's deal with the matrix. We are not going to save W in -matuse-
format, we are going to write it on disk in a way we can read, so I am
going to write two routines, one to write the matrix, another to read it:
function put_a_matrix(string scalar filename, real matrix W)
{
real scalar fh
fh = fopen(filename, "w")
fputmatrix(fh, W)
fclose(fh)
}
real matrix get_a_matrix(string scalar filename)
{
real matrix W
real scalar fh
fh = fopen(filename, "r")
fgetmatrix(fh, W)
fclose(fh)
return(W)
}
With that, we can save our W matrix by coding
put_a_matrix("L:\FDI\Out\weights2rd.mymat", W)
and we now write the final routine, spatlag():
function spatlag(string scalar index, string scalar windex)
{
spatlag_mult(
read_a_matrix("L:\FDI\Out\weights2rd.mymat"),
index,
windex)
)
}
We could presumably improve spatlag() by passing in the filename as an
argument.
-- 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/