开发者

how to fix this list assignment in mathematica

I want to do the following in Mathematica

Table[p[i], {i, -3, 0}] = Flatten[{Table[0, {i, -3, -1}], 1}]

But I got a开发者_运维知识库n error:

Set::write: Tag Table in Table[p[i], {i, -3, 0}] is Protected.

However, it is perfectly fine to do:

{p[-3], p[-2], p[-1], p[0]} = Flatten[{Table[0, {i, -3, -1}], 1}]

Many thanks!


Force the LHS to evaluate into pieces that can be assigned to:

Evaluate[Table[p[i], {i, -3, 0}]] = Flatten[{Table[0, {i, -3, -1}], 1}]


The reason it doesn't work is because Set has attribute HoldFirst. It means that Set[a,stuff] passes symbol a instead of value of a to Set function. As to why it has this attribute, ask yourself: when you do Set[a,stuff], do you want to assign stuff to symbol a, or to the value of a?

In your example, a holds a table of variable names, so you want the value of a and HoldFirst is annoying. However, most of the time a will have a value like 5 and you want a=stuff to assign stuff to symbol a, not to the value 5

A common pattern to get around Holding attributes is the following:

Set@@{Table[p[i], {i, -3, 0}],Flatten[{Table[0, {i, -3, -1}], 1}]}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜