I am interested in efficient element-wise multiplication of matrices with different dimension. Here is my solution:
Matrix 1 with dim = {3, 4, 4}
mat1 = RandomInteger[10, {3, 4, 4}]
(*{{{6, 0, 0, 3}, {3, 7, 6, 4}, {0, 4, 9, 3}, {6, 9, 3, 0}}, {{1, 7, 1,
4}, {3, 7, 6, 2}, {3, 6, 1, 9}, {3, 6, 4, 1}}, {{1, 7, 1, 0}, {4,
3, 9, 2}, {9, 10, 1, 3}, {2, 3, 2, 8}}}*)
Matrix 2 (dimension {4, 4}
):
mat2 = RandomInteger[10, {4, 4}]
(*{{9, 3, 8, 6}, {2, 0, 2, 5}, {9, 8, 5, 9}, {10, 5, 2, 10}}*)
To let each element in mat2
times with the element in the "subset matrix " of mat1
, because the subset has same dimension i.e. {4, 4}
in this case, so the element-wise multiplication is legal:
Result = Table[mat2 * mat1 [[i]], {i, 1, 3}]
(*{{{54, 0, 0, 18}, {6, 0, 12, 20}, {0, 32, 45, 27}, {60, 45, 6, 0}},
{{9, 21, 8, 24}, {6, 0, 12, 10}, {27, 48, 5, 81}, {30, 30, 8, 10}},
{{9, 21, 8, 0}, {8, 0, 18, 10}, {81, 80, 5, 27}, {20, 15, 4, 80}}}*)
but I don't know if there is a better way to do this, especially in terms of achieving better efficiency.