Last active
August 23, 2018 00:20
-
-
Save basilwong/fc3d93dd87ec0e13cedd197778567160 to your computer and use it in GitHub Desktop.
Function that takes a 2d STL vector and converts it to a (SUNDIALS defined) sparse matrix utilizing sundials internal functions.
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
#include <iostream> | |
#include <vector> | |
#include <sunmatrix/sunmatrix_dense.h> // access to dense SUNMatrix | |
#include <sunmatrix/sunmatrix_sparse.h> // access to sparse SUNMatrix | |
// Converts 2d vector into a sparse matrix. This function assumes all the rows | |
// are the same size. | |
SUNMatrix convert_to_sparse(std::vector< std::vector< realtype > > vec) { | |
// Defining the rows and columns. | |
SUNMatrix temp_dense = SUNDenseMatrix(vec.size(), vec[0].size()); | |
realtype **temp_data = SUNDenseMatrix_Cols(temp_dense); | |
// Moving the vector values to the matrix, by element. | |
for (int i = 0; i < vec.size(); i++) { | |
for (int j = 0; j < vec[0].size(); j++) { | |
temp_data[j][i] = vec[i][j]; | |
} | |
} | |
// Printing the 2d vector. | |
std::cout << "2d Vector:\n\n"; | |
for (int i = 0; i < vec.size(); i++) { | |
std::cout << "\n"; | |
for (int j = 0; j < vec[0].size(); j++) { | |
std::cout << vec[i][j] << "\t"; | |
} | |
} | |
std::cout << "\n\n"; | |
std::cout << "Dense Matrix:\n"; | |
SUNDenseMatrix_Print(temp_dense, stdout); | |
// SUNDIALS internal function conversion to sparse matrix. | |
SUNMatrix sparse = SUNSparseFromDenseMatrix(temp_dense, 0, CSR_MAT); | |
std::cout << "Sparse Matrix:\n"; | |
SUNSparseMatrix_Print(sparse, stdout); | |
// Free the memory used by the temporary dense matrix. | |
SUNMatDestroy(temp_dense); | |
return sparse; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment