Skip to content

Instantly share code, notes, and snippets.

@ShivamPR21
Created March 26, 2020 23:40
Show Gist options
  • Save ShivamPR21/cb0c074e9929ab57bad7a280207323e3 to your computer and use it in GitHub Desktop.
Save ShivamPR21/cb0c074e9929ab57bad7a280207323e3 to your computer and use it in GitHub Desktop.
Reads a CSV file into a Eigen Matrix
#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