Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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

share|improve this question
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
    
Somewhat related question –  Leonid Shifrin Dec 16 '12 at 19:07
    
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
show 1 more comment

1 Answer

up vote 10 down vote accepted

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

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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