MathGroup Archive 1995

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Replacing a part of a list/matrix?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg2215] Re: [mg2180] Replacing a part of a list/matrix?
  • From: Allan Hayes <hay at haystack.demon.co.uk>
  • Date: Mon, 16 Oct 1995 11:54:39 -0400

In [mg2180] Replacing a part of a list/matrix?
"O. Lee" <olee at ripco.com> writes

> I am trying to assign a value to a matrix position, such as:
>
>        pop[[ x,y ]] = value
>
> in a module function. When I try manually assigning a value
> to the matrix position outside of the module, it works. When
> I run the function with the statement, Mathematica gives me
> the following error message:
>
> Part::setps:
>
>        {{1, 1, 0, 0}, <<1>>}
>          in assignment of part is not a symbol.
>
> ............
> I appreciate any help. Thanks.


I hope that the following examples may help.

First define pop

In[1]:=
		pop = {1,2};

Example 1:

In[2]:=
		foo[p_] := p[[2]] = 4                     (**)
In[3]:=
		{foo[pop],pop}
	Part::setps: {1, 2} in assignment of part is not a symbol.
Out[3]=
		{4, {1, 2}}

The crucial parts of the evaluation of foo[pop] are
	0. (**) is used with p_ replaced by pop;
	1. pop is evaluated on the *left* to give ,{1,2};
	2. then the symbol  p on the right is replaced by this value 		
	to give
		{1,2}[[2]] = 4
	3. the evaluation of {1,2}[[2]] = 4 causes the message.
Since the symbol pop never got to the right side its value is unchanged

Example 2:

To make a symbol with value {1,4} on the right , we can do this:

In[4]:=
		foo[p_] := {p2 = p; p2[[2]] = 4, p2}
In[5]:=
		{foo[pop],pop}
Out[5]=
		{{4, {1, 4}}, {1, 2}}

Again, the value of pop is not changed.

Example 3:

To actually change the value of the symbol pop, we must prevent the  
evaluation of anything put in place of p_ on the left.
This can be done by giving foo the attribute HoldAll (or HoldFirst)

In[6]:=
		SetAttributes[foo, HoldAll]
In[7]:=
		foo[p_] := {p[[2]] = 4, p}            (****)
In[8]:=
		{foo[pop], pop}
Out[8]=
		{{4, {1, 4}}, {1, 4}}

Here the symbols p on the right of (****) have been replaced by the  
*symbol* pop, not its value; so that we evaluate  pop[[2]] = 4; and  
after this pop  has value {1,4}

Allan Hayes
hay at haystack.demon.co.uk



  • Prev by Date: Re: Constructing Expressions from List Elements
  • Next by Date: Making Mathematica Functions Evaluate Rapidly?
  • Previous by thread: Re: Replacing a part of a list/matrix?
  • Next by thread: Re: Replacing a part of a list/matrix?