# Wrong result given by matrix multiplication

18 views (last 30 days)

Show older comments

I was doing a matrix multiplication with 3 matrices: BT * C * B

BT = [-1 0 3; 0 -3 -1; 4 0 -2; 0 -2 4; 1 0 3; 0 3 1; -4 0 2; 0 2 -4]

C = [32 8 0; 8 32 0; 0 0 12]

B = BT'

The result given by Matlab is:

>> BT * C * B

ans =

140 -12 -200 160 76 12 200 -160

-12 300 -72 144 -60 -300 72 -144

-200 -72 560 -160 56 72 -560 160

160 144 -160 320 128 -144 160 -320

76 -60 56 128 140 60 -56 -128

12 -300 72 -144 60 300 -72 144

200 72 -560 160 -56 -72 560 -160

-160 -144 160 -320 -128 144 -160 320

However, as I calculated the result by hand it gave me:

140 60 -56 -128 -140 -60 56 128

60 300 -72 144 -60 -300 72 -144

-56 -72 560 -160 56 72 -560 160

-128 144 -160 320 128 -144 160 -320

-140 -60 56 128 140 60 -56 -128

-60 -300 72 -144 60 300 -72 144

56 72 -560 160 -56 -72 560 -160

128 -144 160 -320 -128 144 -160 320

As you can see, Matlab gave wrong answers on

ans(2:end, 1)

and

ans(1, 2:end)

but correct on all the other elements ( i.e., ans(1, 1) and ans(2:end, 2:end) ) in the resulting 8-by-8 matrix.

I have checked my hand calculation several times and found nothing wrong in it.

Why do I get this weird behavior? Am I missing something?

Will be very appreciated if someone could correct/clarify me!

##### 0 Comments

### Accepted Answer

Jan
on 25 Mar 2021

Edited: Jan
on 25 Mar 2021

The behavior is not weird, but Matlab calculates the correct results. If your manual computations give you another result, the error is on your side. Let's check this. What is your result for BT * C?

BT * C =

-32 -8 36

-24 -96 -12

128 32 -24

-16 -64 48

32 8 36

24 96 12

-128 -32 24

16 64 -48

Now multiply this with B:

-1 0 4 0 1 0 -4 0

0 -3 0 -2 0 3 0 2

3 -1 -2 4 3 1 2 -4

The element [2,1] is:

[-24, -96, -12] * [-1; 0; 3] = 24 + 0 - 36 = -12

So your 60 cannot be true.

Or do you start with C * B?

-32 -24 128 -16 32 24 -128 16

-8 -96 32 -64 8 96 -32 64

36 -12 -24 48 36 12 24 -48

Seriously, do you really think it is possible, that such a severe bug of Matlab has not been detected in the last 25 years? Matlab uses BLAS libraries to do this, which have been optimized by Intel. You can be sure, that they have tested the code exhaustively.

The is a pattern in your calculation:

ans(1, :) == -ans(5, :)

ans(:, 1) == -ans(:, 5)

This pattern does not occur in the real solution.

##### 3 Comments

Jan
on 25 Mar 2021

### More Answers (0)

### See Also

### Categories

### Products

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!