problem with a sparse Matrix function CSR (Compressed Sparse Row)

14 views (last 30 days)
This is my first time using Matlab , I tried to write a function that gives you CSR (Compressed Sparse Row)
the result are not correct.
I want the result of IA and JA as a vector and NNZ in my matrix is 14
this is my test Marix M = [0, 0, 0, 0, 1 ; 5, 8, 0, 0, 0 ; 0, 0, 3, 0, 0 ; 0, 6, 0, 0, 1]
the result should be
M =
0 0 0 0 1
5 8 0 0 0
0 0 3 0 0
0 6 0 0 1
A = [ 1 5 8 3 6 1 ]
IA = [ 1 2 4 5 7 ]
JA = [ 5 1 2 3 2 5 ]
this the function I wrote or to be precise the code that i took it from python and i tried to write it in matlab
function sparse_CSR2(M)
m = length(M);
i = 1 ;
val = 0 ;
if isempty(M)
n = 0 ;
else
% n = height(M);
[n,~] = size(M);
end
NNZ = 0;
%val = 0;
while i < m
j = 1;
while j < n
if M(i,j)~=0
val=M(i,j);
JA = [j] ;
NNZ = NNZ + 1 ;
end
j=j+1;
end
IA = [NNZ];
i=i+1;
disp(M);
disp(val);
disp(IA);
disp(JA);
end
  1 Comment
soufiane
soufiane on 11 Dec 2022
this is my last code
function sparse_CSR3(M)
m = length(M);
i = 1 ;
%val = 0 ;
k=1;
if isempty(M)
n = 0 ;
else
% n = height(M);
[n,~] = size(M);
[row,col,value]=find(M);
end
NNZ = 0;
JA = zeros(m,1);
IA = zeros(n,1);
val = zeros(n,1);
%val = 0;
while i < n+1
j = 1;
while j < m+1
if M(i,j)~=0
val(k)=M(i,j);
JA(k) = j ;
NNZ = NNZ + 1 ;
k=k+1;
end
j=j+1;
end
IA(i) = NNZ;
i=i+1;
end
disp(M);
disp(val.');
disp(IA.');
disp(JA.');
end
my result is :
0 0 0 0 1
5 8 0 0 0
0 0 3 0 0
0 6 0 0 1
1 5 8 3 6 1
1 3 4 6
5 1 2 3 2 5
the result should be
0 0 0 0 1
5 8 0 0 0
0 0 3 0 0
0 6 0 0 1
1 5 8 3 6 1
1 2 4 5 7
5 1 2 3 2 5

Sign in to comment.

Answers (1)

Prathamesh
Prathamesh on 5 Jun 2025
I understand that you have a function that gives you a Compressed Sparse Row. And you want the result of “IA” and “JA” as a vector and “NNZ” in a matrix.
You can follow below steps to get the CSR(Compressed Sparse Row)
  1. Count all “NNZ_total” (non-zero elements) in a separate loop.
  2. Pre-allocate “A” and “JA” to size “1 x NNZ_total”.
  3. Pre-allocate “IA” to size “1 x (num_rows + 1)”.
  4. Get dimensions: “ [num_rows, num_cols] = size(M) ” .
  5. Set IA(1) = 1.
  6. Inside the row loop (for r = 1:num_rows):
  • set “ IA(r) = k “ before the inner column loop for row r.
  • Increment k only when a non-zero element is found and stored.
7. After all loops, set “ IA(num_rows + 1) = NNZ_total + 1 “.

Categories

Find more on Sparse Matrices in Help Center and File Exchange

Products


Release

R2015a

Community Treasure Hunt

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

Start Hunting!