Discrepancy in sparse matrix math, when NaN's present

50 views (last 30 days)
Matt J
Matt J about 15 hours ago
Edited: Matt J about 8 hours ago
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
result1 = 5×3
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result2=full(D*S) %incorrect
result2 = 5×3
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  5 Comments
Walter Roberson
Walter Roberson 9 minutes ago
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))
D = 2×2 sparse double matrix (1 nonzero)
(1,1) NaN
result1=full(v.*S) %correct
result1 = 2×1
NaN 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result2a=full(D)*(S) %incorrect
result2a = 2×1
0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
result2 = full(result2a)
result2 = 2×1
0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Matt J
Matt J 8 minutes ago
Edited: Matt J 4 minutes ago
Yes, it seems that when S is sparse, all NaNs in the left operand D of D*S are treated as finite, nonzeros.
n = 5;
S = sparse(n, n);
v=nan(n, 1);
D=sparse(diag(v));
testOps(D,S)
ans = "D=full S=full"
DmtimesS = 5×5
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = "D=full S=sparse"
DmtimesS = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = "D=sparse S=full"
DmtimesS = 5×5
NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
ans = "D=sparse S=sparse"
DmtimesS = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
function testOps(D,S)
ops={@full,@sparse};
for i=1:2
L=ops{i};
for j=1:2
R=ops{j};
"D="+func2str(L)+" S="+func2str(R)
DmtimesS=full( L(D)*R(S) ),
end
end
end

Sign in to comment.

Answers (0)

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!