Bookmark and Share

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]

st: Copying structures


From   Matthew White <[email protected]>
To   [email protected]
Subject   st: Copying structures
Date   Mon, 15 Apr 2013 00:26:04 -0400

Hi Statalist members,

I'm using a Mata structure in a function that looks like this:

void function write_lists(struct odklist rowvector lists)
{
    real scalar i
    struct odklist scalar list
    struct odklist rowvector newlists

    newlists = odklist()
    for (i = 1; i <= length(lists); i++) {
        list = lists[i]

        // Modify variable list.

        // If list satisfies certain criteria, add it to newlists.
    }

    // More code

    for (i = 1; i <= length(newlists); i++) {
        // Do stuff with newlists[i].
    }
}

My problem is that over the course of the function, the argument lists
is modified: after each element of lists is copied to list (-list =
lists[i]-), the element is modified whenever list is modified. It's as
if list and lists[i] have been linked.

Here's a simpler example:

mata:

struct point {
    real scalar x, y
}

void function myfunc()
{
    struct point rowvector mypoints

    mypoints = point(2)
    mypoints[1].x = mypoints[1].y = 1
    mypoints[2].x = mypoints[2].y = 2

    liststruct(mypoints)
    mysubroutine(mypoints)
    liststruct(mypoints)
}

void function mysubroutine(struct point rowvector mypoints)
{
    struct point scalar firstpoint

    firstpoint = mypoints[1]
    firstpoint.x = firstpoint.x + 1
}

myfunc()

end

Before -mysubroutine()-, mypoints[1].x = 1. Afterwards, mypoints[1].x
= 2. This is despite the fact that the only use of mypoints is to make
firstpoint a copy of mypoints[1].

It seems to work fine to copy a struct scalar to another struct scalar
or a struct vector to another struct vector, but copying an element of
a struct vector to a struct scalar results in this behavior.

I'm using Stata 12.1 SE on Windows 7. Any suggestions would be much appreciated.

Thanks,
Matt

--
Matthew White
Senior Project Associate
Innovations for Poverty Action
101 Whitney Avenue, New Haven, CT 06510 USA
www.poverty-action.org
*
*   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/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index