1
$\begingroup$

I have some kind of output like this: {{1, 5}, {1, 13}, {1, 5, 25}}. I would like to be able to enter in each sublist and make sums of every two elements in sublists, for example my desired output would be {{6}, {14}, {6, 30, 26}}. I can export these sublists in txt file, but I don't know if this is even necessary.

Is this possible?

Thank you very much on your help!

$\endgroup$
2
  • $\begingroup$ Try a combination of Map and any of the suggestions in your previous question. You are very close. $\endgroup$ Sep 4, 2012 at 14:23
  • $\begingroup$ Welcome to Mathematica.SE! Please consider registering your account so that any upvotes you get on this question are added to those you might get on future questions and answers. That way, over time you will be able to do more on the site (post graphics, edit things, etc). $\endgroup$ Sep 4, 2012 at 18:02

1 Answer 1

7
$\begingroup$

Imagine you have these data:

data = Range /@ Range[2, 5]

{{1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}

Then this will do:

(Plus @@@ Subsets[#, {2}]) & /@ data

{{3}, {3, 4, 5}, {3, 4, 5, 5, 6, 7}, {3, 4, 5, 6, 5, 6, 7, 7, 8, 9}}

Application f@@@expr is equivalent to Apply[f,expr,{1}]. It will simultaneously map over internal elements and replace their heads with f. Using this on you data:

(Plus @@@ Subsets[#, {2}]) & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

With the same success you could use any functions offered to you for your privious answer. For example:

#~Subsets~{2}~Total~{2} & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

or from @Verde & @OleksandrR. comments:

(Total /@ Subsets[#, {2}]) & /@ {{1, 5}, {1, 13}, {1, 5, 25}}

{{6}, {14}, {6, 26, 30}}

$\endgroup$
3
  • 1
    $\begingroup$ Probably (Total /@ Subsets[#, {2}]) & /@ {{1, 5}, {1, 13}, {1, 5, 25}} is faster $\endgroup$ Sep 4, 2012 at 14:50
  • $\begingroup$ @Verde yes, added, thank you. $\endgroup$ Sep 4, 2012 at 14:59
  • 1
    $\begingroup$ Map[Total, Subsets[#, {2}] & /@ {{1, 5}, {1, 13}, {1, 5, 25}}, {2}] works, too. $\endgroup$ Sep 4, 2012 at 22:25

Your Answer

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

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