Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: st: Mata pointers for three dimensional matrices
From
Matthew Baker <[email protected]>
To
[email protected]
Subject
Re: st: Mata pointers for three dimensional matrices
Date
Wed, 19 Feb 2014 13:24:58 -0500
Garrett --
This is a question that comes up every now and then (in fact, I think
I asked it once!). The answer is if you want to hold something in a
pointer, it should probably point to something that is a
function-generated result. So, for example, instead of coding
something like:
\* begin *\
Z=J(3,3,NULL)
for (i=1;i<=3;i++) {
for (j=1;j<=3;j++) {
matToAdd=J(3,3,i)
Z[i,j]=&matToAdd
}
}
You could instead use a function call instead of my matToAdd above,
which is replaced over and over again. Something like:
for (i=1;i<=3;i++) {
for (j=1;j<=3;j++) {
Z[i,j]=&J(3,3,i)
}
}
/*end*/
I have used a function like "transmorphic dummy(X) return(X)" to this
end at times. Another possibility that you might like is to use an
associative array, which has no such difficulty, conceptual or
otherwise. In fact, I think of these as the true generalizations of
matrix ideas to arbitrary generations. For example:
/* begin */
Z=asarray_create("real",2)
for (i=1;i<=3;i++) {
for (j=1;j<=3;j++) {
matToAdd=J(3,3,i)
asarray(Z,(i,j),matToAdd)
}
}
asarray(Z,(1,1))
asarray(Z,(3,3))
/* end */
Hope that helps!
Matt Baker
On Wed, Feb 19, 2014 at 11:37 AM, Garrett Harmon <[email protected]> wrote:
> Hello,
>
> In order to create a three dimensional matrix, I have a vector of
> pointers that point to a working matrix, and I need each pointer to
> store a different state of that matrix. However, since they are
> pointers, they just point to the last transformation done to the
> working matrix. Here's a simple example:
>
> mata
> pointers=J(1,2,NULL)
> calculation=J(1,5,0)
> for (a=1; a <= 2; a++)
> {
> for (i=1; i<=5; i++)
> {
> calculation[1,i]=calculation[
> 1,i]+1
> }
> pointers[1,a]=&calculation
> *pointers[1,a]
> }
> *pointers[1,1]
> end
>
> I want *pointers[1,1] to equal [1 1 1 1 1] and *pointers[1,2] to equal
> [2 2 2 2 2], but after the loop ends they both point to [2 2 2 2 2]
> which is the final state of the calculation matrix. Any thoughts on
> how I should be doing it differently?
>
> -Garrett
> *
> * For searches and help try:
> * http://www.stata.com/help.cgi?search
> * http://www.stata.com/support/faqs/resources/statalist-faq/
> * http://www.ats.ucla.edu/stat/stata/
--
Dr. Matthew J. Baker
Department of Economics
Hunter College and the Graduate Center, CUNY
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/