# Applying a function of several arguments to the rows of a matrix

I have a user-defined function which takes three vectors as input. Suppose that is like this:

f[a_, b_, u_] := Total[a*Total[u]^b]


Usually I have vectors for a and b but a matrix format for u. For example,

a = {1.5, 2, 1}
b = {-1, 1, 0.5}
u = {{1, 2, 0}, {1, 0, 1.5}, {2, 1, 1}}


which should give the result

{8.23205, 7.18114, 10.375}

In other words, the function f should be applied to each row of u. I can do this using a Do loop, but I want to know how to do it using Map or other functional commands (but not Table).

• Have a look at what Total[a*Total[#]^b]&/@u will do. In fact, take a look at the result of Total[#]&/@u to see what this syntax does. – Jonathan Shock May 28 '13 at 23:09

The equivalent to a Do loop using Map is

f[a, b, #] & /@ u


Which gives the desired results:

{8.23205, 7.18114, 10.375}

• It's nice. I was trying MAP[f[a,b,#],u] but it didn't work. I always got confused by pure functions! – Amin May 29 '13 at 1:45
• @Amin You were very close! It can be written Map[f[a, b, #] &, u] -- remember that it's not a pure function until you've marked where it ends, with an ampersand. The highlighting will help you with this, the # will turn from pink to green once you have an & in place. – C. E. May 29 '13 at 2:21

Anon's method is no doubt better but here is another method that may have some interest:

Block[{f, a, b}, Thread @ f[a, b, u]]

{8.23205, 7.18114, 10.375}


This makes f, a, b effectively inert, then uses Thread to distribute across the rows of u. This could also be formulated:

f @@@ Block[{a, b}, Thread@{a, b, u}]


You could also use Outer:

Outer[f, {a}, {b}, u, 1][[1, 1]]

{8.23205, 7.18114, 10.375}


Or a form of Table:

Table[f[a, b, x], {x, u}]

• Thank you Mr.Wizard. Those gave me another insights to the problem. – Amin May 29 '13 at 1:47

Anon's answer is the way I would do it, but it's fun to figure out a solution that works for single vectors as well as a list of vectors:

f[a_, b_, u_] := Map[Composition[#^b &, Total], u, {-2}].a


Examples

f[a, b, u]

{8.23205, 7.18114, 10.375}

f[a, b, First@u]

8.23205