Skip to content

Instantly share code, notes, and snippets.

@KirkWylie
Created December 8, 2011 12:24
Show Gist options
  • Save KirkWylie/1446838 to your computer and use it in GitHub Desktop.
Save KirkWylie/1446838 to your computer and use it in GitHub Desktop.
Sparse Matrix Vector Multiply
final int[] rowPtr = A.getRowPtr(); // get the row pointer
final int[] colIdx = A.getColumnIndex(); // get the column index
final double[] values = A.getNonZeroElements(); // get the nonzero elements
final int rows = A.getNumberOfRows(); // get the number of rows
double[] result = new double[rows]; // allocate memory for the result vector
int ptr = 0; // this indicates where we have got to in the data variable "values"
for (int i = 0; i < rows; i++) { // loop over rows
for (int j = rowPtr[i]; j < rowPtr[i + 1]; j++) { // accessing this many elements in row[i]
result[i] += values[ptr] * x[colIdx[ptr]]; // accumulate the result.
ptr++; // increment the data pointer
}
}
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment