# How can I compute the dot product of an arbitrary number of matrices?

First I make an example with three matrices.

M = {{1, 2}, {3, 4}};
M = {{1.1, 2.1}, {3.1, 4.1}};
M = {{1.2, 2.2}, {3.2, 4.2}};


I want to calculate

M.M.M


so that is my code

For[m = 1, m <= 3, m = m + 1, M1[m] = Dot[M[m], M1[m - 1]]]


where

M1 = {{1, 0}, {0, 1}};


M1 should be the result I want, but When I run the code, the return value is

{{1.2, 2.2}, {3.2, 4.2}}.Dz1


So I want to know: what is wrong in my code and how can I correct it?

• why not M.M.M or Dot[M , M, M]? – kglr Jan 13 '19 at 10:17
• as a matter of fact, the number of the matrix is n (very big), so I must write a code to calculate – 郑新然 Jan 13 '19 at 10:27
• The code DZ1, should be M1 – 郑新然 Jan 13 '19 at 10:29
• Possibly relevant: (83072), (83412), (112125) – Mr.Wizard Jan 13 '19 at 10:56

If you just want a way to generate the dot product of $$n$$ terms, you can use Array to generate the list and Apply Dot to the result:

Dot @@ Array[M, 5]
(* M.M.M.M.M *)


My apologies, when I started writing I had not seen the above answer. I do not delete mine because I also have some comments below, but if a moderator does not agree feel free to delete it.

As a toy example, I set 5 identical matrices {{1,1},{1,2}} and call them A1,..,E1. So list={A1,B1,C1,D1,E1}

Dot @@ list


gives the desired result

{{34, 55}, {55, 89}}

A1.B1.C1.etc or Dot[A1 , B1, C1] do not work for me (maybe I did something wrong), but ((A1.B1).C1).etc does.

As 郑新然 remarked, using an identity matrix as operator in Fold[#1.#2 &, {{1,0},{0,1}}, list] produces the correct result.

{{34, 55}, {55, 89}}

• I think the code Fold[#1.#2 &, 1, list] where 1 should be substitute by the matrix {{1,0},{0,1}}. And still appreciate your attention to this question. – 郑新然 Jan 13 '19 at 13:05
• @郑新然 Correct observation, I changed my answer. Thank you very much. – Titus Jan 13 '19 at 18:45
• @郑新然 Fold[Dot, list] is shorter. – Michael E2 Jan 14 '19 at 1:59