sparse matrix entries are not displayed correctly
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hao Hu
le 28 Avr 2023
Réponse apportée : James Tursa
le 23 Jan 2024
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 commentaires
Walter Roberson
le 28 Avr 2023
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.
Réponse acceptée
Walter Roberson
le 28 Avr 2023
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 commentaires
Plus de réponses (1)
James Tursa
le 23 Jan 2024
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 commentaires
Voir également
Catégories
En savoir plus sur Sparse Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!