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

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


  • 1
    $\begingroup$ Nice question, but please provide copyable code next time. Many people tend to skip questions that require them to type the code themselves. $\endgroup$ – Sjoerd C. de Vries Dec 16 '12 at 14:21
  • $\begingroup$ Somewhat related question $\endgroup$ – Leonid Shifrin Dec 16 '12 at 19:07
  • $\begingroup$ Sjoerd you are absolutely right, I didn't think of that, I'll keep it in mind. Leonid thank you for the link. $\endgroup$ – tst Dec 16 '12 at 23:40
  • $\begingroup$ 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. $\endgroup$ – image_doctor Dec 16 '12 at 23:46
  • $\begingroup$ 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. $\endgroup$ – tst Dec 17 '12 at 11:03

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]]]


  • $\begingroup$ 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. $\endgroup$ – tst Dec 16 '12 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.