Discrepancy in sparse matrix math, when NaN's present
Show older comments
I expect result1 and result2 below to be identical, but they aren't. The discrepancy must be a bug, right? I'm working in R2024b, but the Run output below shows the issue exists as well in whatever the Matlab online engine is now running.
n = 5; m = 3;
S = sparse(n, m);
v=nan(n, 1);
D=sparse(diag(v));
result1=full(v.*S) %correct
result2=full(D*S) %incorrect
8 Comments
Walter Roberson
on 28 Oct 2025
Are you sure that you want I and J to be empty, making S all-zero ?
randperrm(something, something_bigger) gives the empty array.
Matt J
on 28 Oct 2025
It looks like the key is that S is sparse in D*S
n = 2; m = 1;
S = sparse(n, m);
v = zeros(n,1);
v(1) = nan;
D=sparse(diag(v))
result1=full(v.*S) %correct
result2a=full(D)*(S) %incorrect
result2 = full(result2a)
dpb
on 28 Oct 2025
There was a similar thread on sparse performance here just a week or so ago where it ended up being full for similar reasons. I looked but didn't find it in a cursory search, iirc, it was @Steven Lord who pointed out the issue about timing.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements 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!