Statalist The Stata Listserver


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

RE: st: macros & expanding names in mata?


From   "David M. Drukker, StataCorp" <[email protected]>
To   [email protected]
Subject   RE: st: macros & expanding names in mata?
Date   Mon, 06 Mar 2006 11:14:37 -0600

Matissa Hollister <[email protected]> asked about how to store and access
multiple matrices in mata.

Matissa described a macro type solution the problem, while indicating that
this solutions was not feasible because Mata is not a macro language.

Below, I propose a simple solution to Matissa's problem that stores and
accesses the submatrices in one big matrix.

Matissa has two vectors of parameters, say -x- and -y-.  For each
combination of the parameters, Matissa wants to create and store a matrix.

Let's suppose that x is 1 x p, y is 1 x q and that for each (x,y) a function
called dist(x,y) creates an n x m matrix.  The essence of the solution below
is simply to stack the p*q n x m matrices into a big matrix called D.  The
details of storing and retrieving the matrices are in the example code
below.  I have added some comments to explain the process.

clear

mata: 

x = ( 1, 2, 3)
y = ( 4, 5)

// this is just an example function
real matrix dist( real scalar x, real scalar y, real scalar n, real scalar m)
{
	return((1/abs(x-y))*J(n, m, 1))
}

p = cols(x)
q = cols(y)

n = 3
m = 4

// make D to hold individual matrices
// note that the row dimension is p*q*n because we stack the individual 
// matrices

D = J(p*q*n, m, .)

// This loop puts the individual matrices into D
for(i=1; i<=p; ++i) {
	for(j=1; j<=q; ++j) {
		frow = ((i-1)*q +j-1)*n + 1	// first row for this matrix
		lrow = ((i-1)*q +j)*n 	// last  row for this matrix
printf("when i = %1.0f and j = %1.0f, the matrix is\n", i, j)
		dist(x[i], y[j], n, m)
		D[|frow,1 \ lrow,m|] = dist(x[i], y[j], n, m)
	}
}

printf("\n\nD now contains the individual matrices\n")
D

printf("\n\nNow let's retrieve them elements of D and print them out\n")
for(i=1; i<=p; ++i) {
	for(j=1; j<=q; ++j) {
		frow = ((i-1)*q +j-1)*n + 1	// first row for this matrix
		lrow = ((i-1)*q +j)*n 	// last  row for this matrix
		printf("when i = %1.0f and j = %1.0f, the matrix is\n", i, j)
		D[|frow,1 \ lrow,m|] 
	}
}
end

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