Skip to content

Instantly share code, notes, and snippets.

@abikoushi
Last active December 11, 2024 04:29
Show Gist options
  • Save abikoushi/94c764f2df30541972d9f95e30d630e0 to your computer and use it in GitHub Desktop.
Save abikoushi/94c764f2df30541972d9f95e30d630e0 to your computer and use it in GitHub Desktop.
read multiple lines from mtx file (Rcpp)
#include "RcppArmadillo.h"
// [[Rcpp::depends(RcppArmadillo)]]
#include <iostream>
#include <string>
#include <vector>
using namespace Rcpp;
void readmtx(arma::uvec & row_i,
arma::uvec & col_i,
arma::vec & val,
const std::string & readtxt,
const arma::uvec & bag) {
int x;
int y;
double v;
std::ifstream file(readtxt);
std::string str;
int index = 0;
int n = 0;
while (std::getline(file, str)){
if(index == bag(n)+2){
std::stringstream ss(str);
std::vector<std::string> svec;
while( ss.good() ){
std::string substr;
getline(ss, substr, ' ');
svec.push_back(substr);
}
x = stoi(svec[0]);
y = stoi(svec[1]);
v = stod(svec[2]);
row_i(n) = x-1;
col_i(n) = y-1;
val(n) = v;
n++;
}
index++;
if(n>=bag.n_rows){
break;
}
}
}
// [[Rcpp::export]]
List readmtx2(const std::string & readtxt,
const arma::uvec & bag){
arma::uvec row_i(bag.n_rows);
arma::uvec col_i(bag.n_rows);
arma::vec val(bag.n_rows);
readmtx(row_i,col_i,val, readtxt, bag);
return List::create(row_i, col_i, val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment