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.

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

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

1 Answer 1

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}]
Normal[%]
{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.