Skip to content

Instantly share code, notes, and snippets.

@nicolamontecchio
Created May 17, 2016 16:15
Show Gist options
  • Save nicolamontecchio/05bc917cc2dce36c7a3425d14d3f76bf to your computer and use it in GitHub Desktop.
Save nicolamontecchio/05bc917cc2dce36c7a3425d14d3f76bf to your computer and use it in GitHub Desktop.
read a matrix of floats in tsv format
typedef struct _FloatMatrix {
uint32_t N;
uint32_t M;
float *data;
} FloatMatrix;
/* read matrix from tsv file */
/* matrix is allocated, will need to be freed */
FloatMatrix * read_txt_float_matrix(char *fpath)
{
uint32_t R, C;
R = 0; C = 0;
FILE *fp = fopen(fpath, "r");
if(!fp)
{
fprintf(stderr, "cannot open %s for reading\n", fpath);
return NULL;
}
// number of columns
rewind(fp);
uint32_t first_line_len = 0;
while(1)
{
char c = fgetc(fp);
if(c == '\n')
{
C++;
break;
}
else if(c == '\t')
C++;
first_line_len++;
}
rewind(fp);
uint32_t n_max_rows = 4096;
FloatMatrix *X = (FloatMatrix *) malloc(sizeof(FloatMatrix));
X->data = (float *) malloc(sizeof(float) * n_max_rows * C);
uint32_t i = 0;
while(!feof(fp))
{
for(uint32_t j = 0; j < C; j++)
{
fscanf(fp, "%f ", X->data + i*C + j);
/* printf("%f ", *(X->data + i*C + j)); */
}
/* printf("\n"); */
i++;
if(i == n_max_rows)
{
/* printf("reallocing\n"); */
n_max_rows *= 2;
X->data = realloc(X->data, sizeof(float) * n_max_rows * C);
}
}
X->N = i;
X->M = C;
// TODO trim the data ... (not strictly necessary)
/* printf("first line len is %d, matrix is: %d x %d\n", first_line_len, X->N, X->M); */
fclose(fp);
return X;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment