# st: Matrix transformation

 From "Glenn Goldsmith" To Subject st: Matrix transformation Date Sat, 4 Apr 2009 00:08:03 +0100

```Hi Susan,

As far as I'm aware Stata/Mata don't really do sparse matrix storage, but
you can otherwise replicate the behavior of sparse() with the following mata
function:

********* Begin code **************
mata:
real matrix sparse(real matrix x)
{
real matrix y
real scalar k

y = J(colmax(x[,1]),colmax(x[,2]),0)
for (k=1; k<=rows(x); k++) {
y[x[k,1],x[k,2]] = y[x[k,1],x[k,2]] + x[k,3]
}

return(y)
}
end
********* End code ****************

You can then call this either from within mata:

y = sparse(x)

or within stata:

mata : st_matrix("y",sparse(st_matrix("x")))

(in both cases assuming that your input matrix is called x, and output
matrix is called y).

HTH,

Glenn

"Susan Olivia" <olivia@primal.ucdavis.edu> wrote:

Dear all,

I would like to transform a say 4272 x 3 matrix (this matrix
basically tells us the distance between each pairs of
observation) onto 1068 x 1068.

In MATLAB, this can be transformed using the following
command:

W4NN = sparse(GIS_4NN(:,1), GIS_4NN(:,2), GIS_4NN(:,3));

Is there any equivalent command like the above in STATA?

Any tips on this much appreciated.

Thanks,

Susan

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/
```