Search code examples
matlabmatrixmultiplicationfloating-accuracy

Problem of difference in between matrix multiplication done by * and by components by components by hand (MATLAB)


I have a problem with the accuracy of matrix multiplication on Matlab. I will explain this with an example. Let

 A=[0.1256, 0.25789; 0.00018, 0.68741];
B=[0.1578, 0.24471; 0.12801, 0.99701];
s=0;
while s<100
    for i=1:2
        for j=1:2
    A(i,j)=A(i,j)+0.0125;
    B(i,j)=B(i,j)+0.2470;
        end
    end
    D=A*B;
    d11=A(1,1)*B(1,1)+A(1,2)*B(1,2);
    d12=A(1,1)*B(1,2)+A(1,2)*B(2,2);    
    d21=A(2,1)*B(1,1)+A(2,2)*B(1,2);
    d22=A(2,1)*B(2,1)+A(2,2)*B(2,2);
    DD=[d11, d12; d21, d22];
    s=s+1;
end

I have an algorithm where the values of matrix A and B components are upgraded at each iteration. In this algorithm, there is also a formula that involves the definition of a matrix as the product of the upgraded A and B.

My problem is if I define at each iteration these new matrix components by components executing by hand the matrix multiplication I would obtain a result slight different with respect to the case I define this new matrix by execution of matrix multiplication done by Matlab by "*" and not components by components by me. The final result is:

DD=[71,8082684418998,   73,0622074848998;
79,4048550050998,   80,8251256858998]
and
D=[71,6322976788998 73,0622074848998
79,1787592580998    80,9710216918998]

Can it be possible? Thanks in advance


Solution

  • This has not to do with numerical accuracy, but your manual matrix multiplication is wrong. This would be the correct version:

    d11=A(1,1)*B(1,1)+A(1,2)*B(2,1);
    d12=A(1,1)*B(1,2)+A(1,2)*B(2,2);    
    d21=A(2,1)*B(1,1)+A(2,2)*B(2,1);
    d22=A(2,1)*B(1,2)+A(2,2)*B(2,2);
    

    But you see that it is easy to make mistakes in this manual matrix multiplication, so best to just do A*B.