9

I have two list which are not equal dimension:

listA = {{{1, 2}, {2, 2}, {3, 4}}, {{1, 1}, {2, 2}, {3, 3}}};
listB = {{4, 4}, {5, 5}};

And I want to divide them or multiply the such as the results has the same dimensions, for the first dimension, it should look like:

(#*listB[[1]]) & /@ listA[[1]]

but I would like to do it all at once so that the result has the same dimension as listA. I bet it has probably been answered here but I cannot seem to find it. Therefore link to an existing answer is also great.

user64494
  • 26,149
  • 4
  • 27
  • 56
atapaka
  • 3,954
  • 13
  • 33

4 Answers4

5

Some overhead but the most clean solution I could muster:

Diagonal@Outer[Times, listB, listA, 1, 2]

{{{4, 8}, {8, 8}, {12, 16}}, {{5, 5}, {10, 10}, {15, 15}}}

V.E.
  • 1,700
  • 17
  • 16
3

Using Simon Woods's smartThread one may write:

smartThread[listA*listB, 1]
{{{4, 8}, {8, 8}, {12, 16}}, {{5, 5}, {10, 10}, {15, 15}}}

For fun here is a way using Inactive and Activate, assuming list elements are atomic:

Map[Inactive, Quiet[listA*listB], {-2}] // Activate
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
1
a = {{{1, 2}, {2, 2}, {3, 4}}, {{1, 1}, {2, 2}, {3, 3}}};
b = {{4, 4}, {5, 5}};

With ReplacePart and Threaded (new in 13.1)

ReplacePart[i_ :> a[[i]] * Threaded @ b[[i]] @ a

{{{4, 8}, {8, 8}, {12, 16}}, {{5, 5}, {10, 10}, {15, 15}}}

eldo
  • 67,911
  • 5
  • 60
  • 168
1

Using KroneckerProduct and TensorRank:

listA = {{{1, 2}, {2, 2}, {3, 4}}, {{1, 1}, {2, 2}, {3, 3}}};
listB = {{4, 4}, {5, 5}};

tr = TensorRank[listA];

{#[[1]][[;; tr]], #[[-1]][[;; tr]]} &@KroneckerProduct[listB, listA]

({{{4, 8}, {8, 8}, {12, 16}}, {{5, 5}, {10, 10}, {15, 15}}})

E. Chan-López
  • 23,117
  • 3
  • 21
  • 44