# Calculating products of given length of two matrices

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.

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

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}]

• 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. – Marko Feb 4 '16 at 11:18
• What about if I want to multiply every matrix in my list by a given matrix $C$? – Marko Feb 4 '16 at 11:30
• @Marko c.#& /@ list. Look up Map and Function. – Szabolcs Feb 4 '16 at 11:31
• 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. – Marko Feb 4 '16 at 17:10
• @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). – Szabolcs Feb 4 '16 at 17:33