Created
April 7, 2017 19:12
Compressed Sparse Row (CSR) Matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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