3
$\begingroup$

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.
$\endgroup$
  • 1
    $\begingroup$ Table[b[[i]].a[[i]].b[[i]], {i, 1, 3}] or #[[2]].#[[1]].#[[2]] & /@ Transpose[{a, b}]. $\endgroup$ – corey979 Mar 18 at 21:06
  • $\begingroup$ Thanks a lot corey979! $\endgroup$ – Ghady Mar 19 at 0:30
8
$\begingroup$

Using MapThread and Dot:

MapThread[Dot, {b, a, b}]
$\endgroup$
  • $\begingroup$ Thank you very much, It is the easiest! $\endgroup$ – Ghady Mar 19 at 0:33
6
$\begingroup$

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

$\endgroup$
  • $\begingroup$ Thank you very much! $\endgroup$ – Ghady Mar 19 at 0:31
  • $\begingroup$ You're welcome. $\endgroup$ – Henrik Schumacher Mar 19 at 8:00

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.