# How to multiply nested lists by a list with the same length?

Here's the expected output:

{{a, b}, {c, d}, {e, f}} * {3, 4} = {{3a, 4b}, {3c, 4d}, {3e, 4f}}


However, the code above will multiply each element of the encompassing list (3 elements) by {3, 4} (2 elements) and cause an error.

I've tried defining a function and using Map, but I'm sure there's a more elegant way of doing this speedily, without needing to first define a function.

{3, 4} # & /@ {{a, b}, {c, d}, {e, f}}


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

Alternative forms:

Map[{3, 4} # &][{{a, b}, {c, d}, {e, f}}]


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

Map[{3, 4} # &, {{a, b}, {c, d}, {e, f}}]


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

• Works perfectly. If anyone else is wondering, the multiplication sign is not required here, but you can also modify this to perform other basic operations such as addition by placing the operator between the slot: {3, 4} + #. Or to add subtract square root: {3, 4} - Sqrt[#]. – WeavingBird1917 Nov 28 '18 at 5:14
{{a, b}, {c, d}, {e, f}}.DiagonalMatrix[{3, 4}]


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

A fairly straightforward method is to use ScalingTransform:

ScalingTransform[{3,4}] @ {{a,b},{c,d},{e,f}}


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

It is not as fast as using a double Transpose (@Thies) or Dot (@Henrik) though:

list = RandomReal[1, {10^6, 3}];
scale = RandomReal[1, 3];

r1 = list . DiagonalMatrix[scale]; //RepeatedTiming
r2 = Transpose[scale Transpose[list]]; //RepeatedTiming
r3 = ScalingTransform[scale] @ list; //RepeatedTiming

r1 === r2 === r3


{0.0075, Null}

{0.018, Null}

{0.2, Null}

True

Inner[Times, {{a, b}, {c, d}, {e, f}}, {3, 4}, List]


Dear @WeavingBird1917 you can use Table for your purpose.

list={{a, b}, {c, d}, {e, f}};

result=Table[
{3*list[[i,1]],4*list[[i,2]]}
,{i,1,Length[list]}
]


If you want to change multiplication with summation, subtraction or division, you need only change the * sign with +, - or /.

You can also use Transpose to bring the matrix into a shape where the multiplication by {3,4} vectorises over the columns and then Transpose again to bring it back into the original shape:

Transpose[{3, 4} Transpose[{{a, b}, {c, d}, {e, f}}]]


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

or if we want to save a level of paranthesis, we can use the EsctrEsc shortcut to get the postfix version of Transpose:

Transpose[{3, 4} {{a, b}, {c, d}, {e, f}}EsctrEsc]

{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}

If we find ourselves using the double transpose pattern a lot we could also make this into a neat operator:

Transposed[f_Function] := Transpose[f[Transpose[#]]] &
Transposed[{3, 4} # &][{{a, b}, {c, d}, {e, f}}]


{{3 a, 4 b}, {3 c, 4 d}, {3 e, 4 f}}