5
$\begingroup$

Suppose we want to get the dot product for the following lists aa and bb, whose elements (a, b, etc.) are also lists. We can get the symbolic expression of aa.bb first, and then assign numerical values of the elements in aa and bb.

aa = {{a, b}, {c, d}};
bb = {{{a, b}, {c, d}}, {{a, b}, {c, d}}};
cc = aa.bb;
(* -> {{{a^2 + a b, a b + b^2}, {a c + b c, a d + b d}}, {{a c + a d, b c + b d}, {c^2 + c d, c d + d^2}}} *)
a = b = c = d = {1, 2, 3}
cc
(* -> {{{{2, 8, 18}, {2, 8, 18}}, {{2, 8, 18}, {2, 8, 18}}}, {{{2, 8, 18}, {2, 8, 18}}, {{2, 8, 18}, {2, 8, 18}}}} *)

However, if we do not want to get the symbolic expression for aa.bb (because it is too long in some situations), and only use numerical calculations, we cannot directly use Dot in the same way as follows. Is there a simple way to fix this?

aa = {{a, b}, {c, d}};
bb = {{{a, b}, {c, d}}, {{a, b}, {c, d}}};
a = b = c = d = {1, 2, 3};
cc = aa.bb
(* -> Dot::dotsh: Tensors {{{1,2,3},{1,2,3}},{{1,2,3},{1,2,3}}} and {{{{1,2,3},{1,2,3}},{{1,2,3},{1,2,3}}},{{{1,2,3},{1,2,3}},{{1,2,3},{1,2,3}}}} have incompatible shapes. >> *)
$\endgroup$
4
  • $\begingroup$ Have you seen Inner[]? $\endgroup$ Jun 19, 2015 at 15:21
  • $\begingroup$ Dot works as you desire only when the dimensions are compatible; for example, with a=b=c=d={1,2}. $\endgroup$
    – Ian
    Jun 19, 2015 at 15:26
  • $\begingroup$ Related: Easy way to perform multiplication of two 2x2 matrices, that contain list elements?, but in a sense answer there uses kind of intermediate symbolic representation, so it might not be a best answer to this question. $\endgroup$
    – jkuczm
    Jun 20, 2015 at 9:46
  • $\begingroup$ @Guesswhoitis. Can this be done with inner? I thought so too, but cant make it work. $\endgroup$
    – george2079
    Jun 20, 2015 at 13:35

2 Answers 2

2
$\begingroup$

not pretty but there is always this:

 Table[Sum[aa[[i, j]] bb[[j, k, l ]],{j,2}],{i,2},{k,2},{l,2}]
$\endgroup$
1
$\begingroup$

If the entire symbolic product is too large perhaps it is sufficient to work in chunks:

aa = {{a, b}, {c, d}};
bb = {aa, aa};

rule = a | b | c | d -> {1, 2, 3};
Table[x.y /. rule, {x, aa}, {y, bb\[Transpose]}]
{{{{2, 8, 18}, {2, 8, 18}}, {{2, 8, 18}, {2, 8, 18}}},
 {{{2, 8, 18}, {2, 8, 18}}, {{2, 8, 18}, {2, 8, 18}}}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.