0
$\begingroup$

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.

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

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}
$\endgroup$

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