# The multiplication of list of matrices

I need to multiply 3 lists of matrices (b.a.b) as the following code

a = {{{-17.8227277373099, -1.6565234964560602},
{-1.6565234954649242,
5.298073701591974}}, {{-17.812203521929003,
-1.5013126607114478}, {-1.5013126574896714,
4.384050851253119}}, {{-17.801677045750512,
-1.4055541329078751}, {-1.405554138172727,
3.869511752542245}}};

b = {{{0.8409518416651456, 0}, {0,
0.1274293000222242}}, {{0.8409815693580924, 0}, {0,
0.14187218616724442}}, {{0.841011296000238, 0}, {0,
0.15290209433231844}}};


I used the following:

  mat = b.a.b


But, I think this way is not correct because I didn't get the result. Also, I make a test for the first matrices as the following code, that what I wanted to get for the whole matrices multiplication.

 a1 = {{-17.8227277373099, -1.6565234964560602},
{-1.6565234954649242, 5.298073701591974}};

b1 = {{0.8409518416651456, 0}, {0, 0.1274293000222242}};

mat1 = b1.a1.b1

{{-12.6042, -0.177516}, {-0.177516, 0.0860313}}

Thanks.

• Table[b[[i]].a[[i]].b[[i]], {i, 1, 3}] or #[[2]].#[[1]].#[[2]] & /@ Transpose[{a, b}]. Mar 18, 2019 at 21:06
• Thanks a lot corey979! Mar 19, 2019 at 0:30

Using MapThread and Dot:

MapThread[Dot, {b, a, b}]

• Thank you very much, It is the easiest! Mar 19, 2019 at 0:33

If you need it really fast, then use Compile:

n = 1000000;
a = RandomReal[{-1, 1}, {n, 2, 2}];
b = RandomReal[{-1, 1}, {n, 2, 2}];

cf = Compile[{{a, _Real, 2}, {b, _Real, 2}},
b.a.b,
RuntimeAttributes -> Listable,
Parallelization -> True
];

MapThread[Dot, {b, a, b}]; // AbsoluteTiming // First
cf[a, b]; // AbsoluteTiming // First


1.46343

0.075722

• Thank you very much! Mar 19, 2019 at 0:31
• You're welcome. Mar 19, 2019 at 8:00