11

I need to store a rather big number of variables and I tried to do that by storing each variable as Z[n] with varying n. I guess this was not my best idea. The first problem I encountered is when I tried to check whether Z[n] is set. As you can see at the picture if I do this inside a loop it is always true and outside a loop it is the correct value. Why is this happening? I have mathematica 8.0.4.0.

(I had no idea how should I have tagged the question. Feel free to change them.)

Output

Simon Woods
  • 84,945
  • 8
  • 175
  • 324
tst
  • 953
  • 6
  • 13
  • 1
    Nice question, but please provide copyable code next time. Many people tend to skip questions that require them to type the code themselves. – Sjoerd C. de Vries Dec 16 '12 at 14:21
  • Sjoerd you are absolutely right, I didn't think of that, I'll keep it in mind.

    Leonid thank you for the link.

    – tst Dec 16 '12 at 23:40
  • Have you thought about creating your variables with z=Table[Unique[],{numVariables}] then you can have x[[1]],z[[2]],... or Table[Unique["z"],{numVariables}] to give z1,z2,z3,.... Though the exact numbering of the latter depends upon the existence of any already defined zs. – image_doctor Dec 16 '12 at 23:46
  • It's not very convenient. I actually have a series $\sum_{n=1}^\infty z_n t^{-n}$ so the numbering and the order is very important for me. I don't really like the way I store the data, but works fairly well. – tst Dec 17 '12 at 11:03
  • Is there any way to create algorithmically variables z1, z2, z3, etc with numbers I choose? The only other option I know is to use Subscript. – tst Dec 17 '12 at 11:16

1 Answers1

13

ValueQ[Z[sindex]] is equivalent to !Hold[Evaluate[Z[sindex]]]===Hold[Z[sindex]] which evaluates to !(Hold[Z[1]]===Hold[Z[sindex]]). Since lhs and rhs of the latter are not literally the same the result combined with Not is True.

This has nothing to do with being inside the loop or not. If you try ValueQ[Z[sindex]] outside the loop you get the same result. Note that you didn't test that, but instead assumed that ValueQ[Z[1]] would be equivalent. It's the presence of the '1' that makes the difference here.

The ValueQ documentation page provides a warning about this pitfall in the "Possible Issues" section:

ValueQ returns True if any evaluation takes place

A workaround in this case would be the use of With to inject the actual value of sindex in the expression to be tested.

With[{sindex = sindex}, ValueQ[Z[sindex]]]

False

Sjoerd C. de Vries
  • 65,815
  • 14
  • 188
  • 323
  • Thank you very much, I wasted quite a few frustrating hour with this and yet I failed to check what ValueQ[Z[sindex]] evaluates to. – tst Dec 16 '12 at 23:42