Kindt
Kindt

Reputation: 41

Matlab matrix multiplication returns values that it shouldn't

I have a problem using matrix multiplication in Matlab.

I have a 8x4 matrix called A and a 4x1 vector called B. Looking at matrix A, the fourth row of has the values

A(4,:) = (-19.723654104483987, -73.609679228848705,  73.609679228848705,  19.723654104483987)

and the vector B has the values

B = (101325,      101325,      101325,      101325)'.

It appears to me that these two, when multiplied, would cancel eachother out. However, when I use A*B = ans, the fourth row of ans has a value as shown below.

ans(4) = 4.656612873077393e-10 

I find this strange since I tried to check if the elements of A(4,:) and they really should cancel out since

(A(4,1) == -A(4,4)) = 1
(A(4,2) == -A(4,3)) = 1

and

(B(1) == B(2)) = 1
(B(1) == B(3)) = 1
(B(1) == B(4)) = 1

I was thinking that it might have something to do with the machine epsilon of Matlab, but the answer is larger than e-16.

Another thing I find strange is that when I use A(4,:)*B it returns 0. Why does a value appear on the forth row when using full scale matrix multiplication?

If anyone has an idea why this doesn't return zero, I would be grateful!

Upvotes: 0

Views: 76

Answers (1)

Lutz Lehmann
Lutz Lehmann

Reputation: 25972

You are computing an expression

((-a+(-b))+b)+a,  a,b > 0

Floating point operations are not commutative, the truncation error committed by the first addition of -a and -b is not undone by the second addition of b, so the third addition of a will not land at zero, but will reflect the truncation error of the first sum. So it is not surprising that you get a residual error of size (a+b)*mu, mu being the machine constant, about 2e-16. As your a+b is about 1e+7, this conforms with the actual result you got.

See also the many resources provided in Is floating point math broken?

Upvotes: 2

Related Questions