sparse matrix entries are not displayed correctly
1 次查看(过去 30 天)
显示 更早的评论
A sparse matrix variable has a very strange behavior.
A minimal example is given as follows: this is a 2 by 4 matrix, and I display them in both full and sparse ways for clarification
>> full(A)
ans =
0 0 0 198844
0 0 0 23672
>> A
A =
(2,4) 23672
(1,4) 198844
The problem is: if we print the first row, then it shows tht the first row contains zeros, which is not true.
>> A(1,:)
ans =
All zero sparse: 1×4
However, the second rows are printed correctly, and if we print both first&second rows and fouth column, it is also correct.
>> A(2,:)
ans =
(1,4) 23672
>> A(1:2,4)
ans =
(2,1) 23672
(1,1) 198844
remarks:
- These commands are entered without doing anything in between.
- A(1,4) is also considered as zero if I make any calculations, for example, A(1,4)*5 gives zero.
2 个评论
Walter Roberson
2023-4-28
A = sparse([ 0 0 0 198844
0 0 0 23672])
A(1,:)
A(2,:)
Could you save the matrix to a .mat file and attach the mat file for testing?
Also, please fill out which Release you are using.
采纳的回答
Walter Roberson
2023-4-28
Notice that the matrix is displayed out of order -- the normal order is linear indexing, so (1,4) would have appeared before (2,4)
I suspect that the matrix was created by third-party software that (somehow) did not follow internal rules about constructing sparse matrices.
load('example_sp_A.mat')
A
B = sparse(full(A))
A(1,:)
B(1,:)
mask = A ~= B
full(mask)
nnz(mask)
So we can construct a "repaired" version of the matrix by taking it full, but in the meantime working with A gets us messed up results, such as a sparse array that has two elements both at the same location.
In summary, I think A was constructed corrupted, either by a third party routine writing a corrupted .mat or else by a malfunctioning mex routine.
4 个评论
更多回答(1 个)
James Tursa
2024-1-23
I finally finished my sparse matrix integrity checker. You can find it in the FEX under the name SAREK (I think you will be able to figure out the inside joke):
Here is what is reports for the posted matrix:
>> sarek(A)
SAREK -- Sparse Analyzer Real Et Komplex , by James Tursa
Compiled in version R2023a (with -R2018a option)
Running in version R2023a
Matrix is double ...
Matrix is real ...
M = 2 >= 0 OK ...
N = 4 >= 0 OK ...
Nzmax = 2 >= 1 OK ...
Jc[0] == 0 OK ...
Jc[N] = 2 <= Nzmax = 2 OK ...
Jc array OK ...
ERROR: There are 1 Ir entries out of order or out of range
TO FIX: [M,N] = size(A); [I,J,V] = find(A); B = sparse(I,J,V,max(max(I),M),N);
All stored elements nonzero OK ...
There were ERRORS found in matrix!
ans =
1
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!