3
$\begingroup$

I have the following problem to solve. Let us have two given square matrices $A$ and $B$ of the same size and a positive integer $n$. I would like to produce all products of length at most $n$ of matrices $A$ and $B$ in all orders. I came up with the following code:

allProducts[a_, b_, n_] := 
 Module[{set = {a, b}, set1, set2, i = 1}, 
  While[i <= n - 1, set1 = Thread[Dot[set, a]] ;
   set2 = Thread[Dot[set, b]] ; set = Union[set, set1, set2]; i++]; 
  set]

This code works prefectly symbolically for any $n$ i can think of. However when I have concrete matrices $A$ and $B$ lets say of size $2\times 2$, allProducts[a,b,4] gives errors

Dot::rect: Nonrectangular tensor encountered.

hread::tdlen: Objects of unequal length in (My matrices appear here)

Thanks for the help.

$\endgroup$
  • 2
    $\begingroup$ Dot @@@ Tuples[{a, b}, 5] should do it. $\endgroup$ – Szabolcs Feb 4 '16 at 11:04
5
$\begingroup$

The problem is that Dot[a,b] (a and b being atomic, e.g. symbols with no values) evaluates differently than Dot[{a,b},{x,y}] (i.e. the arguments being lists).

Dot[{a, b}, x] does not evaluate, so you can transform it using Thread. Dot[{a, b}, {x, y}] does evaluate before it even sees Thread. Dot[{a, b}, {x, y, z}] tries to evaluate and gives up with an error.

This explains the problems you see.


A simpler possible implementation is

kProducts[a_, b_, k_] := Dot @@@ Tuples[{a, b}, k]
allProducts[a_, b_, n_] := Catenate@Table[kProducts[a,b,k], {k, n}]
$\endgroup$
  • $\begingroup$ Thank you. This works now. When I calculated symbolically, it worked and beacuse of this I could not find the error. I am quite new @Mathematica. $\endgroup$ – Marko Feb 4 '16 at 11:18
  • $\begingroup$ What about if I want to multiply every matrix in my list by a given matrix $C$? $\endgroup$ – Marko Feb 4 '16 at 11:30
  • 1
    $\begingroup$ @Marko c.#& /@ list. Look up Map and Function. $\endgroup$ – Szabolcs Feb 4 '16 at 11:31
  • $\begingroup$ Thanks again. It seems easy when you look at worked examples from a book but when you try to work it on your own things get hard. $\endgroup$ – Marko Feb 4 '16 at 17:10
  • $\begingroup$ @Marko Yes, it takes a while to get used to thinking in terms of these constructs. As I remember I enjoyed working through this a long time ago (though my memory might be failing me and maybe it's not as detailed after all). $\endgroup$ – Szabolcs Feb 4 '16 at 17:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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