How can I express multiplication of an array and a matrix so that
{x, y, z}*{{10, 20, 30}, {0, 1, 2}}
gives
{{10 x, 20 y, 30 z}, {0, y, 2 z}}
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI think the answers given in the comments to the question deserves being on record as a formal answer.
{x, y, z}*# & /@ {{10, 20, 30}, {0, 1, 2}}
{{10, 20, 30}, {0, 1, 2}}.DiagonalMatrix[{x, y, z}]
Inner[Times, {{10, 20, 30}, {0, 1, 2}}, {x,y,z}, List]
EDIT: Comparing the timings:
Clear["Global`*"]
n = 20; r = 100;
var = Array[x, n];
mat = Array[m, {r, n}];
t[1] = AbsoluteTiming[prod[1] = var*# & /@ mat;][[1]]
(* 0.001768 *)
t[2] = AbsoluteTiming[prod[2] = mat.DiagonalMatrix[var];][[1]]
(* 0.027773 *)
t[3] = AbsoluteTiming[prod[3] = Inner[Times, mat, var, List];][[1]]
(* 0.001384 *)
Comparing the timings
(t /@ Range[3])/t[3]
(* {1.27746, 20.0672, 1.} *)
Verifying that the different approaches provide identical results.
Equal @@ (prod /@ Range[3])
(* True *)
{{10, 20, 30}, {0, 1, 2}}.DiagonalMatrix[{x,y,z}]==Inner[Times, {{10, 20, 30}, {0, 1, 2}}, {x,y,z}, List]==Inner[Times, {{10, 20, 30}, {0, 1, 2}}, DiagonalMatrix[{x,y,z}]]
but timings may be important
$\endgroup$
m.DiagonalMatrix[v] == Inner[Times, m, DiagonalMatrix[v]] == Inner[Times, m, v, List]
, where m is matrix, v is vector
$\endgroup$
Perhaps something as simple as this, which can be more efficient for large elements:
(a*{b, c}) /. {a -> {x, y, z}, b -> {10, 20, 30}, c -> {0, 1, 2}}
(* {{10 x, 20 y, 30 z}, {0, y, 2 z}} *)
{x, y, z}*# & /@ {{10, 20, 30}, {0, 1, 2}}
$\endgroup${{10, 20, 30}, {0, 1, 2}}.DiagonalMatrix[{x, y, z}]
$\endgroup$