Skip to content

Instantly share code, notes, and snippets.

@totherik
Created April 7, 2017 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save totherik/adafae2855c7bc33ba1e4b8c396eadec to your computer and use it in GitHub Desktop.
Save totherik/adafae2855c7bc33ba1e4b8c396eadec to your computer and use it in GitHub Desktop.
Compressed Sparse Row (CSR) Matrix
// https://en.wikipedia.org/wiki/Sparse_matrix#Compressed_sparse_row_.28CSR.2C_CRS_or_Yale_format.29
function csr(matrix) {
const A = [];
const IA = [0];
const JA = [];
const nnz = [];
for (const [ index, row ] of matrix.entries()) {
nnz[index] = 0;
for (const [ column, value ] of row.entries()) {
if (value !== 0) {
A.push(value);
JA.push(column);
nnz[index] += 1;
}
}
IA[index + 1] = IA[index] + nnz[index];
}
return [ A, IA, JA ];
}
function uncsr([ A, IA, JA ]) {
const result = [];
let count = 0;
for (const [ index, value ] of IA.entries()) {
if (index < IA.length - 1) {
result[index] = [];
const row = JA.slice(value, IA[index + 1]);
for (const pos of row) {
result[index][pos] = A[count];
count += 1;
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment