# What's wrong with my rule? [duplicate]

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.

-

## 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 (->) –  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]] –  belisarius May 19 '14 at 14:37
Also covered here: (18487) (20736) (25652) –  Mr.Wizard May 19 '14 at 20:23

## 1 Answer

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

Normal[%]

{0, 0, 3, 4, 5}

-