10
$\begingroup$

Given two nested lists

alist={{a,b,c},{d,e,f}}
blist={{r,s,t},{x,y,z}}

How can I get

res={{a r,b s,c t},{a x,b y,c z},{d r,e s,f t},{d x,e y,f z}} 

where juxtaposition is the product of those two elements?

I've played around with Outer, Map, etc., etc., but I can't get what I am looking for.

$\endgroup$
7
  • 8
    $\begingroup$ You shouldn't have given up on Outer[] too soon: Flatten[Outer[Times, {{a, b, c}, {d, e, f}}, {{r, s, t}, {x, y, z}}, 1], 1]. $\endgroup$ Commented Feb 16, 2023 at 13:23
  • $\begingroup$ @J.M.'spersistentexhaustion Maybe I need your persistent exhaustion. I have a train to catch in a few mins but I assume your method works. Thanks. $\endgroup$
    – 1729taxi
    Commented Feb 16, 2023 at 13:26
  • 8
    $\begingroup$ try also Times @@@ Tuples[{alist, blist}] $\endgroup$
    – kglr
    Commented Feb 16, 2023 at 13:48
  • 3
    $\begingroup$ Inner[Times, alist, #, Plus] & /@ blist // Flatten[#, 1] & $\endgroup$
    – Syed
    Commented Feb 16, 2023 at 13:51
  • 2
    $\begingroup$ @Syed We need to replace the Plus with List - as in Inner[Times, alist, #, List] & /@ blist // Flatten[#, 1] & --- Not sure how to highlight in grey. $\endgroup$
    – 1729taxi
    Commented Feb 16, 2023 at 20:47

5 Answers 5

13
$\begingroup$
Times @@@ Tuples @ {alist, blist}
{{a r, b s, c t}, {a x, b y, c z}, {d r, e s, f t}, {d x, e y, f z}}
$\endgroup$
2
  • 2
    $\begingroup$ I'll accept this answer - as I said above - nice and succinct. Thanks. $\endgroup$
    – 1729taxi
    Commented Feb 16, 2023 at 21:00
  • $\begingroup$ Also very fast, I think $\endgroup$
    – user1066
    Commented Feb 17, 2023 at 15:21
9
$\begingroup$
Distribute[{alist,blist}, List, List,List, Times]

(* {{a r, b s, c t}, {a x, b y, c z}, {d r, e s, f t}, {d x, e y, f z}} *)
$\endgroup$
8
$\begingroup$

Using TensorProduct:

Join @@ (Transpose@*Diagonal /@ Map[Transpose, TensorProduct[alist, blist], {2}])

(*{{a r, b s, c t}, {a x, b y, c z}, {d r, e s, f t}, {d x, e y, f z}}*)

Or using KroneckerProduct:

Map[Composition[Diagonal, Partition[#, {Last@Dimensions[{alist, blist}]}] &], KroneckerProduct[alist, blist]]

(*{{a r, b s, c t}, {a x, b y, c z}, {d r, e s, f t}, {d x, e y, f z}}*)
$\endgroup$
7
$\begingroup$

In addition to the solution in the comments the following

l1 = {{a, b, c}, {d, e, f}};
l2 = {{r, s, t}, {x, y, z}};
Join @@ Table[l1[[i]] l2[[j]], {i, 1, Length@l1}, {j, 1, Length@l2}]

also does the trick.

$\endgroup$
3
$\begingroup$
al = {{a, b, c}, {d, e, f}};

bl = {{r, s, t}, {x, y, z}};

Using J.M's comment and Catenate

Catenate @ Outer[Times, al, bl, 1]

{{a r, b s, c t}, {a x, b y, c z}, {d r, e s, f t}, {d x, e y, f z}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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