problem with a sparse Matrix function CSR (Compressed Sparse Row)
显示 更早的评论
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 个)
Prathamesh
2025-6-5
0 个投票
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)
- Count all “NNZ_total” (non-zero elements) in a separate loop.
- Pre-allocate “A” and “JA” to size “1 x NNZ_total”.
- Pre-allocate “IA” to size “1 x (num_rows + 1)”.
- Get dimensions: “ [num_rows, num_cols] = size(M) ” .
- Set IA(1) = 1.
- 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 “.
类别
在 帮助中心 和 File Exchange 中查找有关 Sparse Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!