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

조회 수: 7 (최근 30일)
soufiane
soufiane 2022년 12월 8일
답변: Prathamesh 2025년 6월 5일
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
soufiane
soufiane 2022년 12월 11일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Prathamesh
Prathamesh 2025년 6월 5일
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 “.

카테고리

Help CenterFile Exchange에서 Sparse Matrices에 대해 자세히 알아보기

제품


릴리스

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by