0
$\begingroup$

I would like to sum elements of a vector variable, e.g., Is

xvec = Array[x, 10]
s24 = Sum[xvec[i], {i, 2, 4}]

where $s_{24}:=\sum_{i=2}^4 x_i$. However, I am returned a "Recursion limit". What did I do wrong?enter image description here

$\endgroup$
1
  • 2
    $\begingroup$ (1) The error most likely comes from a latent definition. Try ClearAll[xvec, x] and re-executing. Or quit and restart the kernel. (2) Distinguish the syntax for a function call xvec[i] from extracting a Part xvec[[i]]. You want the latter. $\endgroup$
    – Michael E2
    May 29 at 14:58

1 Answer 1

1
$\begingroup$

You should use Span to retrieve elements from index 2 to 4. Also note that accessing list elements by indices in Mathematica requires double square brackets (see Part).

Total[xvec[[2 ;; 4]]]
(* x2 + x3 + x4 *)

Alternatively, you cal also use Sum, but again – mind the double square brackets.

Sum[xvec[[i]], {i, 2, 4}]
(* x2 + x3 + x4 *)
$\endgroup$
1
  • 2
    $\begingroup$ Or s24 = Sum[x[i], {i, 2, 4}] $\endgroup$
    – Bob Hanlon
    May 29 at 14:57

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