29 void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs,
const mxArray *prhs[]) {
30 if (nrhs < 1 || nrhs > 4 || nlhs != 2) {
31 mexErrMsgTxt(
"Usage: [numbers, text] = swallow_csv(filename, [quote, [sep, [escape]]])");
34 for (
int i = 0; i < nrhs; i++) {
35 if (!mxIsChar(prhs[i]) || mxIsEmpty(prhs[i])) {
36 mexErrMsgTxt(
"Usage: [numbers, text] = swallow_csv(filename, [quote, [sep, [escape]]])");
45 quote = mxGetChars(prhs[1])[0] & 0xff;
47 sep = mxGetChars(prhs[2])[0] & 0xff;
49 escape = mxGetChars(prhs[3])[0] & 0xff;
55 mxGetString(prhs[0], filename, 1024);
56 FILE *
f = fopen(filename,
"rb");
58 mexErrMsgTxt(
"Couldn't open specified file");
62 vector<vector<string> > data;
65 size_t max_columns = 0;
68 size_t n = fread(buf, 1, 4096, f);
72 for (
size_t i = 0; i < n; i++) {
75 if (buf[i] == quote) {
77 }
else if (buf[i] == sep) {
80 }
else if (buf[i] ==
'\r') {
82 }
else if (buf[i] ==
'\n') {
85 if (row.size() > max_columns) {
86 max_columns = row.size();
95 if (buf[i] == escape) {
97 }
else if (buf[i] == quote) {
106 }
else if (buf[i] ==
't') {
108 }
else if (buf[i] ==
'r') {
110 }
else if (buf[i] == quote) {
113 mexErrMsgTxt(
"Encountered unknown escape sequence.");
118 if (buf[i] == quote) {
132 mwSize dims[] = {(mwSize) data.size(), (mwSize) max_columns};
133 plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
134 plhs[1] = mxCreateCellArray(2, dims);
136 double *p = mxGetPr(plhs[0]);
138 for (
int i = 0; i < data.size(); i++) {
139 vector<string> &row(data[i]);
140 for (
int j = 0; j < row.size(); j++) {
141 char *nptr = (
char*) row[j].c_str();
143 double d = strtod(nptr, &endptr);
144 if (row[j].size() == 0 || endptr != nptr + row[j].size()) {
145 p[j * data.size() + i] =
NaN;
146 mxArray *tmp = mxCreateString(nptr);
147 mxSetCell(plhs[1], (
int)(j * data.size() + i), tmp);
149 p[j * data.size() + i] = d;
152 for (
int j = row.size(); j < max_columns; j++) {
153 p[j * data.size() + i] =
NaN;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])