Different matrix multiplication results from the sparse and full version of the same matrix

2 views (last 30 days)
Hello everyone,
I found that for some matrix, if its sparse form and full form multiplied by the same vector, it could get the different results:
clearvars
v1 = [0 0 1 0 1 3;0 0 0 0 0 0];
v2 = sparse(v1);
gene = sqrt([2 3 5 7 11 13])';
disp(v1*gene==v2*gene)
The code above generates 0 1, which means that the first element of the matrix multiplication is inconsistent.
However if you have only v1 = [0 0 1 0 1 3], which is the inconsistent line, it gets correct again.
I've tried it on matlab 2016a,2017b,2019a,all got 0 and 1.
How spooky it is ! Can anybody tells me why it is like this?

Accepted Answer

Alex Mcaulley
Alex Mcaulley on 11 Jun 2019
That is the floating point error (it is not related with sparse or full matrix). See this:
clearvars
v1 = [0 0 1 0 1 3;0 0 0 0 0 0];
v2 = sparse(v1);
gene = sqrt([2 3 5 7 11 13])';
v1*gene-v2*gene
ans =
1.0e-14 *
0.3553
0
Then, the command "==" is not a good idea to deal with this. Use ismembertol for example:
ismembertol(v1*gene,v2*gene,eps)
ans =
2×1 logical array
1
1

More Answers (0)

Categories

Find more on Operating on Diagonal Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!