Reputation: 172
I have a function f[d_]
. My intention is to apply this function to a list as a whole.
Say, d={1,2,3,...}
, then f[d]
gives me a result (a number or whatever). Until here, everything is clear.
Now lets say I have the following list of lists: p={l1,l2,l3,...}
Is there a more efficient way than Map to compute f[p]
, where the expected result is {f[l1],f[l2],f[l3],...}
?
For example, with the Sin[x]
function, Mapping it over a list is way slower than just putting the list inside its argument. This doesn't seem to work with my function f[d]
and the list of lists p. What should I do to make that work? Would it be faster than Map?
To make myself clearer, say
f[d_]:=Total[d]
Then, f[{a1,a2,a3}] gives me a1+a2+a3, as expected.
But, f[{{a1, a2, a3}, {b1, b2, b3}, {c1, c2, c3, c4}}] kills the machine.
Thank you!
Upvotes: 2
Views: 325
Reputation: 6989
Sorry Listable doesnt do the job here.. You can put map inside the function if it helps..
ClearAll[f]
f[d_List] := Map[ Total, d, {-2}]
f[{1, 2, 3}]
f[{{1, 2, 3}, {4, 5}}]
f[{{{1, 2, 3}, {4, 5}}, {{6}, {7, 8}}}]
(* 6 *)
(* {6, 9} *)
(* {{6, 9}, {6, 15}} *)
Upvotes: 0
Reputation: 1519
When I change your code, It gives:
Total[{{a1, b1, c1}, {b1, b2, b3}, {c1, c2, c3}}]
{a1 + b1 + c1, b1 + b2 + c2, b3 + c1 + c3}
When Total take a list argument, It just add the members, in your case, It adds
{a1, b1, c1},{b1, b2, b3}, {c1, c2, c3}
But they are not the same dimension, so you cant get the right answer.
In this case,Map should be used.
Map[Total,{{a1, b1, c1}, {b1, b2, b3}, {c1, c2, c3, c4}}]
or
Plus @@@ {{a1, b1, c1}, {b1, b2, b3}, {c1, c2, c3, c4}}
Upvotes: 1