How to create a CRS structure in Matlab using val, rind, and cind.

19 Ansichten (letzte 30 Tage)
Grace Meek
Grace Meek am 14 Jun. 2022
Bearbeitet: Karan Singh am 4 Okt. 2023
I am needing to create a CRS structure (compressed row storage) in Matlab using val, rind, and cind for a singular matrix (not any matrix operations). I understand how the CRS structure works and what the output is meant to be. However, every time I try to try to code it, I cannot get it right. This is the reference article I am using to help me: http://www.netlib.org/utk/people/JackDongarra/etemplates/node373.html You can use any matrix as an example. I can adapt it to fit the problem I am working on.
I am new to Matlab, so this is where my inexperience kicks in. Any advice, tips, suggestions, etc. on just where to begin with the code would be greatly appreciated. Thank you.

Antworten (1)

Karan Singh
Karan Singh am 4 Okt. 2023
Bearbeitet: Karan Singh am 4 Okt. 2023
Hi Grace,
From what I understand, the goal is to create a MATLAB code that can generate the CRS structure for any given matrix.
Let's break down the steps to implement the CRS structure based on the reference article you provided:
  • Initialize the CRS structure:
  • Create three empty arrays:“val,rind, andcind.
  • valwill store the non-zero values of the matrix.
  • “rindwill store the row indices corresponding to the non-zero values.
  • cindwill store the column indices corresponding to the non-zero values.
  • Traverse the matrix:
  • Iterate over each row of the matrix.
  • Within each row, iterate over each column.
  • If the element at the current position is non-zero, store its value in thevalarray.
  • Store the row index in therindarray.
  • Store the column index in thecindarray.
  • Finalize the CRS structure:
  • After traversing the entire matrix, store the total number of non-zero elements in a variable,nnz.
  • Append a zero at the end of thevalarray.
  • Append the valuennzat the end of therindarray.
  • Append the valuennzat the end of thecindarray.
Here's an example implementation:
% Example matrix
matrix = [1 0 0 0; 0 2 0 0; 3 0 4 0; 0 0 0 5];
% Initialize CRS structure
val = [];
rind = [];
cind = [];
% Traverse the matrix
[nrows, ncols] = size(matrix);
nnz = 0; % Number of non-zero elements
for i = 1:nrows
for j = 1:ncols
if matrix(i, j) ~= 0
val = [val matrix(i, j)];
rind = [rind i];
cind = [cind j];
nnz = nnz + 1;
end
end
end
% Finalize CRS structure
val = [val 0];
rind = [rind nnz];
cind = [cind nnz];
% Display the CRS structure
disp("val: " + mat2str(val))
disp("rind: " + mat2str(rind))
disp("cind: " + mat2str(cind))
Attached below are some documentation links that you may find helpful:
Hope this helps!
Karan Singh Khati

Community Treasure Hunt

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

Start Hunting!

Translated by