Created
March 26, 2020 23:40
-
-
Save ShivamPR21/cb0c074e9929ab57bad7a280207323e3 to your computer and use it in GitHub Desktop.
Reads a CSV file into a Eigen Matrix
This file contains 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 <fstream> | |
#include <Eigen/Dense> | |
Eigen::MatrixXd readCSV(std::string file, int rows, int cols) { | |
std::ifstream in(file); | |
std::string line; | |
int row = 0; | |
int col = 0; | |
Eigen::MatrixXd res = Eigen::MatrixXd(rows, cols); | |
if (in.is_open()) { | |
while (std::getline(in, line)) { | |
char *ptr = (char *) line.c_str(); | |
int len = line.length(); | |
col = 0; | |
char *start = ptr; | |
for (int i = 0; i < len; i++) { | |
if (ptr[i] == ',') { | |
res(row, col++) = atof(start); | |
start = ptr + i + 1; | |
} | |
} | |
res(row, col) = atof(start); | |
row++; | |
} | |
in.close(); | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment