2
$\begingroup$

I am new to Mathematica and I would like to find out how to use Map on a function with two parameters such as:

function[a_, b_] := (Return[a+b])

Something like this is what I need:

Map[function,{{1,2,3,4,5},{1,2,3,4,5}}]

I want Mathematica to compute 1+1, then 2+2 and so on.

Sorry for the noob question, but I found nothing in the reference

$\endgroup$
5
  • 5
    $\begingroup$ Try MapThread instead of Map $\endgroup$
    – kglr
    Apr 25, 2016 at 18:02
  • 1
    $\begingroup$ aside, just do function[a_, b_] := a+b. Return is needed in mathematica very rarely and often does not behave as you might expect. $\endgroup$
    – george2079
    Apr 25, 2016 at 18:09
  • 1
    $\begingroup$ Indeed, in Mathematica you should almost never use Return in the way it is used in other languages. For your specific example, just run a+b when the lists a and b are separate (not grouped into another list). $\endgroup$ Apr 25, 2016 at 18:12
  • $\begingroup$ Thanks to all of you...i do my best not to annoy you With noob questions..thanks again $\endgroup$
    – Damm Joe
    Apr 25, 2016 at 18:17
  • $\begingroup$ Use Apply instead of Map, try function @@@ Transpose[{{1,2,3,4,5},{1,2,3,4,5}}] $\endgroup$
    – Jason B.
    Apr 25, 2016 at 19:09

1 Answer 1

3
$\begingroup$

The simplest way is to use Thread

f[a_, b_] := a + b
Thread[f[{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}]]

{2, 4, 6, 8, 10}

And just to show you a little more Mathematica kung-foo, consider:

g[a_, b_] /; a < b := Row[{a, " is less than ", b}]
g[a_, b_] /; a > b := Row[{a, " is greater than ", b}]
g[a_, b_] /; a == b := Row[{a, " is equal to ", b}]

With[{nums = Range[5]}, Column @ Thread[g[nums, Reverse[nums]]]]

result

Not at all like java or c++, but once you get into it, actually a lot nicer.

$\endgroup$
2
  • $\begingroup$ Why is the Thread needed? Just using f[{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}] also gives {2, 4, 6, 8, 10}. $\endgroup$
    – bill s
    Apr 25, 2016 at 20:42
  • $\begingroup$ 'Plus' is Listable so Thread is not required for the specific case but woukd be for the more general case @Bills $\endgroup$ Apr 26, 2016 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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