sparse matrix entries are not displayed correctly
Show older comments
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 Comments
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.
Hao Hu
on 28 Apr 2023
Accepted Answer
More Answers (1)
James Tursa
on 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
Categories
Find more on Matrix Indexing 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!