Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate list of products from elements of a pair of lists in mathematica

Is there a pre-canned operation that would take two lists, say

a = { 1, 2, 3 }
b = { 2, 4, 8 }

and produce, without using a for loop, a new list where corresponding elements in each pair of lists have been multiplied

{ a[1] b[1], a[2] b[2], a[3] b[3] }

I was thinking there probably exists something like Inner[Times, a, b, Plus], but returns a list instead of a sum.

like image 782
Peeter Joot Avatar asked Nov 29 '22 03:11

Peeter Joot


2 Answers

a = {1, 2, 3}
b = {2, 4, 8}

Thread[Times[a, b]]

Or, since Times[] threads element-wise over lists, simply:

a b

Please note that the efficiency of the two solutions is not the same:

i = RandomInteger[ 10, {5 10^7} ];
{First[ Timing [i i]], First[ Timing[ Thread[ Times [i,i]]]]}

(*
-> {0.422, 1.235}
*)

Edit

The behavior of Times[] is due to the Listable attribute. Look at this:

SetAttributes[f,Listable];
f[{1,2,3},{3,4,5}]
(*
-> {f[1,3],f[2,4],f[3,5]}
*)
like image 148
Dr. belisarius Avatar answered Mar 13 '23 10:03

Dr. belisarius


You can do this using Inner by using List as the last argument:

In[5]:= Inner[Times, a, b, List]

Out[5]= {2, 8, 24}

but as others already mentioned, Times works automatically. In general for things like Inner, it's frequently useful to test things with "dummy" functions to see what the structure is:

In[7]:= Inner[f, a, b, g]

Out[7]= g[f[1, 2], f[2, 4], f[3, 8]]

and then work backwards from that to determine what the actual functions should be to give the desired result.

like image 34
Brett Champion Avatar answered Mar 13 '23 10:03

Brett Champion