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

1 次查看(过去 30 天)
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?

采纳的回答

Alex Mcaulley
Alex Mcaulley 2019-6-11
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Sparse Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by