0
$\begingroup$

I'm trying to build a generic function that will calculate sums on different iterators. To simplify let consider:

Sum[x1 + x2 + x3, {x2, 2}, {x3, 2}];

MySum := Function[ Sum[x1 + x2 + x3, ##]];
(* I can call this function like this *)
MySum[{x2, 2}, {x3, 2}];

(*Now let's try an expression*)
xpr = {{x2, 2}, {x3, 2}};
(*Below still works*)
MySum [xpr[[1]], xpr[[2]] ]

(*How to make it generic for an arbitary number of elements?*)
imax = 2; 
MySum [For[ i = 1, i <= imax, i++, xpr[[i]] ] ] 

I would like to be able to call the function for 1 or 2 elements of the list generically.

$\endgroup$
1
  • $\begingroup$ Your function is only adding up lists starting at 1, so on way to do this is by simply using Plus, Apply, Total, and Range like this MySum := Function[Plus @@@ (Range /@ ##) // Total]. Forget x1, x2, x3, etc and just send a list to MySum $\endgroup$ Commented Feb 26, 2019 at 4:12

1 Answer 1

1
$\begingroup$

This should work for any length of the xpr list:

MySum @@ xpr

Call just with the first element of xpr:

MySum @@ xpr[[{1}]]

Call just with the first, third, and fifth element of xpr:

MySum @@ xpr[[{1,3,5}]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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