6
$\begingroup$

Please, for the two lists

L1 = {{a, b}, {c, d}}
L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}}

The desired result is

{{{ae, bf}, {ag, bh}}, {{ci, dj}, {ck, dq}}}
$\endgroup$
  • $\begingroup$ One tangential comment, for a list with constant values, use Set (=) not SetDelayed (:=). $\endgroup$ – JungHwan Min Dec 18 '16 at 0:51
  • $\begingroup$ Also, do you mean {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}} (b h instead of c h) $\endgroup$ – JungHwan Min Dec 18 '16 at 0:53
  • $\begingroup$ Yes , i meant that $\endgroup$ – Ali Dec 18 '16 at 1:01
6
$\begingroup$

One way would be

l1 = {{a,b},{c,d}};
l2 = {{{e,f},{g,h}},{{i,j},{k,q}}};

Partition[Riffle[l1,l1],2] l2
(* {{{a e, b f},{a g, b h}},{{c i, d j},{c k, d q}}} *)

The idea behind this solution is to expand l1 into the same shape as l2

Partition[Riffle[l1,l1],2]
(* {{{a,b},{a,b}},{{c,d},{c,d}}} *)

and then use Mathematicas builtin elementwise multiplication on similar shaped lists to get the result.

Another possible solution:

MapTimes[x_,{y_,z_}] := {x y,x z}
MapTimes @@@ Transpose[{l1,l2}]
(* {{{a e, b f},{a g, b h}},{{c i, d j},{c k, d q}}} *)
$\endgroup$
  • $\begingroup$ It works, thanks for your recommendations $\endgroup$ – Ali Dec 18 '16 at 1:58
  • $\begingroup$ Glad it works for you! $\endgroup$ – Thies Heidecke Dec 18 '16 at 2:00
6
$\begingroup$
L1 = {{a, b}, {c, d}}
L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}}

Transpose[L1 Transpose[L2, {1, 3, 2}], {1, 3, 2}]

{{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}}

$\endgroup$
  • $\begingroup$ Thanks, it is the most appropriate answer for general case $\endgroup$ – Ali Dec 18 '16 at 3:00
6
$\begingroup$
L1 = {{a, b}, {c, d}};
L2 = {{{e, f}, {g, h}}, {{i, j}, {k, q}}};

Transpose /@ (L1*(Transpose /@ L2))

(*  {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}}  *)

or

Thread /@ (L1*(Thread /@ L2))

(*  {{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}}  *)

% == %%

(*  True  *)
$\endgroup$
2
$\begingroup$
Flatten[ Flatten[L2, {{1}, {3}}] L1, {{1}, {3}}]

or

Function[x, # x] /@ #2 & @@@ Thread[{L1, L2}]

{{{a e, b f}, {a g, b h}}, {{c i, d j}, {c k, d q}}}

$\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.