Re: Set::setps problems
- To: mathgroup at smc.vnet.net
- Subject: [mg90270] Re: Set::setps problems
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Fri, 4 Jul 2008 03:56:39 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <g4i94f$3d2$1@smc.vnet.net>
� wrote:
> I found troubles with such a loop:
>
> T = Table[{s, 0}, {s, -Pi, Pi, step}];
>
> For[i = 1, i <= Length[UU], i += 1,
> UU[[i]][[2]] += 5];
>
> (it's just the example of some general idea of changing values of
> table's elements inside a loop)
>
> And Mathematica returned:
>
> Set::setps: UU[[i]] in the part assignment is not a symbol. >>
> Set::setps: UU[[i]] in the part assignment is not a symbol. >>
> Set::setps: UU[[i]] in the part assignment is not a symbol. >>
> General::stop: Further output of Set::setps will be suppressed during \
> this calculation. >>
You cannot use the shortcut += in this case because Mathematica
mismatches the value of the symbol for the symbol itself when expanding
the LHS (say, UU[[1,2]] == 5, so UU[[1,2]] += 5 is rewritten as 5 = 5 +
5 rather than the intended UU[[1,2]] = 5 + 5). So just write the
expanded version UU[[i, 2]] = UU[[i, 2]] + 5.
In[1]:= With[{step = .5}, UU = Table[{s, 0}, {s, -Pi, Pi, step}]]
For[i = 1, i <= Length[UU], i++, UU[[i, 2]] = UU[[i, 2]] + 5]
UU
Out[1]= {{-3.14159, 0}, {-2.64159, 0}, {-2.14159, 0}, {-1.64159,
0}, {-1.14159, 0}, {-0.641593, 0}, {-0.141593, 0}, {0.358407,
0}, {0.858407, 0}, {1.35841, 0}, {1.85841, 0}, {2.35841,
0}, {2.85841, 0}}
Out[3]= {{-3.14159, 5}, {-2.64159, 5}, {-2.14159, 5}, {-1.64159,
5}, {-1.14159, 5}, {-0.641593, 5}, {-0.141593, 5}, {0.358407,
5}, {0.858407, 5}, {1.35841, 5}, {1.85841, 5}, {2.35841,
5}, {2.85841, 5}}
Note that a *much* more efficient way of doing the above is to
manipulate a list as a whole:
In[4]:= UU[[All, 2]] = UU[[All, 2]] + 5
UU
Out[4]= {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}
Out[5]= {{-3.14159, 10}, {-2.64159, 10}, {-2.14159, 10}, {-1.64159,
10}, {-1.14159, 10}, {-0.641593, 10}, {-0.141593, 10}, {0.358407,
10}, {0.858407, 10}, {1.35841, 10}, {1.85841, 10}, {2.35841,
10}, {2.85841, 10}}
You should spend some time familiarizing yourself with "List
Manipulation" and "Functional Programming", as starters, to get an
overall idea on how to program efficiently with Mathematica.
guide/ListManipulation
guide/FunctionalProgramming
Regards,
-- Jean-Marc