Re: Structure modification and related questions
- To: mathgroup at smc.vnet.net
- Subject: [mg13887] Re: [mg13857] Structure modification and related questions
- From: David Withoff <withoff>
- Date: Sun, 6 Sep 1998 02:55:26 -0400
- Sender: owner-wri-mathgroup at wolfram.com
> Hello,
>
> I am working with a big structure (actually, it is a list), like
>
> x=Table[i, {i,10000}]
>
> Q.1) Can I modify x[[3]], let's say, without having to create another
> list of 10000 elements? (the obvious thing for me to try, x[[3]]=0,
> does not work).
Assignment to x[[3]] is smart enough not to make a copy unless it is
necessary. It is necessary to make a copy unless there are no other
uses of the list. For example, in
In[1]:= Module[{x,m},
x=Table[Random[],{10000}];
m=MemoryInUse[];
x[[3]]=1.0;
MemoryInUse[]-m
]
Out[1]= -4
the memory hardly changes, since it is not necessary to make a copy of
the list, but in
In[2]:= Module[{x,y,m},
x=Table[Random[],{10000}];
y=x;
m=MemoryInUse[];
x[[3]]=1.0;
MemoryInUse[]-m
]
Out[2]= 40032
it is necessary to copy the list, because there are two pointers to the
same list (from x and y).
> Q.2) In the same spirit, are there any functions similar to Insert and
> Delete, that modify directely the expression affected by them, without
> taking a whole copy?
No. The only way to do this is with part assignment (as in the above
example, since that is the only operation that simultaneously modifies
an expression and removes the previous use of the expression.
> Q.3) Related to Q.1&2, is it possible in Mathematica that two structures
> (or lists, for that sake) have some parts in common? What I mean by
> this is that, for example, I would like to have the variable x equal to
> the second element of {1,{2,3},4}, so that in case the 3 is changed by
> a 5 in one of them, it is also changed in the other one.
In other programming languages this is typically done with pointers. A
Mathematica expression is a pointer, so:
In[3]:= x = {2, 3}; expr := {1, x, 4}
In[4]:= expr
Out[4]= {1, {2, 3}, 4}
In[5]:= x[[2]] = 5 ;
In[6]:= expr
Out[6]= {1, {2, 5}, 4}
> Thank you for any help you can give me on this
>
> Roberto Moriyon
>
> Roberto Moriyon
> Departamento de Ingenieria Informatica Universidad Autonoma de Madrid
> 28049 Madrid
>
> Phone: +34-91-397-4350
> Fax: +34-91-397-5277
Dave Withoff
Wolfram Research