8
$\begingroup$

I have two lists, e.g.

a = {1,2,3}

b = {4,5,6}

I'd like to multiply each element from the first list with each element from the second, like this:

{1*4, 2*4, 3*4, 1*5, 2*5, 3*5, 1*6, 2*6, 3*6}

I only need the result:

{4, 5, 6, 8, 10, 12, 15, 18}

I have found a solution for this:

Drop[Flatten[Reap[For[i = 1, i < 4, i++, Sow[i*{4, 5, 6}]]]], 1]

However, I think this is overly complicated -- and number 12 is in there two times. Isn't there a much simpler way to do this? Multiply two lists?

$\endgroup$
  • $\begingroup$ Union @@ Outer[Times, {1, 2, 3}, {4, 5, 6}] $\endgroup$ – mathe Aug 31 '18 at 3:18
3
$\begingroup$

Another way to produce the result you seek is:

DeleteDuplicates[Flatten[Table[i*j, {i, a}, {j, b}]]]

{4, 5, 6, 8, 10, 12, 15, 18}

This will also work, and generalizes easily to more than two lists:

DeleteDuplicates[Flatten[TensorProduct[a, b]]]

TensorProduct runs in time similar to KronekerProduct and Outer.

$\endgroup$
10
$\begingroup$
a = {1, 2, 3};
b = {4, 5, 6};
Flatten[KroneckerProduct[a, b]]

{4, 5, 6, 8, 10, 12, 12, 15, 18}

Use DeleteDuplicates to, well, delete duplicates.

$\endgroup$
10
$\begingroup$
DeleteDuplicates @ Flatten @ Outer[Times, a, b] 

{4, 5, 6, 8, 10, 12, 15, 18}

Also, shorter but much slower

DeleteDuplicates[Times @@@ Tuples @ {a, b}]

{4, 5, 6, 8, 10, 12, 15, 18}

Note: If speed is a concern, then Outer, KroneckerProduct and TensorProduct are much faster than Table and Tuples methods:

SeedRandom[1]
{a, b} = RandomInteger[100, {2, 1500}];
r1 = DeleteDuplicates @ Flatten @ Outer[Times, a, b]; // RepeatedTiming // First

0.0103

r2 = DeleteDuplicates[Times @@@ Tuples @ {a, b}]; // RepeatedTiming // First 

0.92

r3 = DeleteDuplicates[Flatten[Table[i*j, {i, a}, {j, b}]]]; // RepeatedTiming // First  

0.78

r4 = DeleteDuplicates @Flatten[KroneckerProduct[a, b]]; // RepeatedTiming // First   

0.011

r5 = DeleteDuplicates[Flatten[TensorProduct[a, b]]]; // RepeatedTiming // First

0.011

r1 == r2 == r3 == r4 == r5

True

$\endgroup$

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.