Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

Consider a simple code to form a SparseArray:

Q = 5;
a = Table[i, {i, Q}];
SparseArray[{{j_} /; j > 2 -> a[[j]]}, {Q}]

Part::pspec: Part specification j is neither a machine-sized integer nor a list of machine-sized integers. >>

What is wrong with the rule? It seems I can not address any matrix element without getting such a warning. Sorry for such a minor question.

share|improve this question

marked as duplicate by Mr.Wizard May 19 '14 at 20:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Use RuleDelayed (:>) instead of Rule (->) – Dr. belisarius May 19 '14 at 14:07
Thank you very much! It works. But why? – Yasha Gindikin May 19 '14 at 14:31
Because you've to "wait" until each j is instantiated to be able to evaluate a[[j]] – Dr. belisarius May 19 '14 at 14:37
Also covered here: (18487) (20736) (25652) – Mr.Wizard May 19 '14 at 20:23
up vote 3 down vote accepted

As Belisarius says in a comment, usingRuleDelayed (:>) instead ofRule (->) will fix your code.

Q = 5;
a = Table[i, {i, Q}];
SparseArray[{{j_} /; j > 2 :> a[[j]]}, {Q}]
SparseArray[<3>, {5}]
{0, 0, 3, 4, 5}
share|improve this answer

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