2
$\begingroup$

I want to take a nested list and replace each sub-list with an arithmetic operation on its elements. For example: a={{1,3},{2,2},{2,3}}. I want to get {4,4,5}. I can do it by: f{x_,y_}=x+y and then Map[f,a] but I suspect that there has to be an easier way by applying rules or similar.

$\endgroup$
2
  • 1
    $\begingroup$ Map is the straightforward way to go. You can use pure functions instead of defining f[x, y]. In this particular case, Plus @@@ a works. In pure functions: (#1 + #2) & @@@ a. $\endgroup$
    – corey979
    Feb 15, 2018 at 5:58
  • $\begingroup$ Total with a level spec is designed for this purpose ..as per Carls answer $\endgroup$ Feb 15, 2018 at 6:51

1 Answer 1

2
$\begingroup$

For your example you can use Total:

a = {{1,3},{2,2},{2,3}};

Total[a, {2}]

{4, 4, 5}

Another possibility is to use Dot:

a . {1,1}

{4, 4, 5}

$\endgroup$

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.