numtools

perform numerical operations on vectors and matrices in unix pipes
git clone git://src.adamsgaard.dk/numtools # fast
git clone https://src.adamsgaard.dk/numtools.git # slow
Log | Files | Refs | README | LICENSE Back to index

commit 3754eed5a3af82a84848f545bd45adc8193b17c3
parent 9dc61cb5c221a9fef82704d7edd23c8f61608ca1
Author: Anders Damsgaard <anders@adamsgaard.dk>
Date:   Mon,  9 May 2022 15:07:48 +0200

put read and save of input matrix into util function

Diffstat:
Mtranspose.c | 23++++-------------------
Mutil.c | 30++++++++++++++++++++++++++++++
Mutil.h | 1+
3 files changed, 35 insertions(+), 19 deletions(-)

diff --git a/transpose.c b/transpose.c @@ -8,28 +8,14 @@ int main(void) { - size_t i = 0, j = 0, nf = 0, nr = 0, linesize = 0; - char *line = NULL, *data = NULL; - double val, **vals = NULL; + size_t i, j, nf, nr; + double **vals = NULL; if (pledge("stdio", NULL) == -1) err(2, "pledge"); - vals = calloc(1, sizeof(double *)); - while (getline(&line, &linesize, stdin) > 0) { - if (nr > 0) - if (!(vals = xreallocarray(vals, nr + 1, sizeof(double *)))) - err(1, "reallocarray"); - if ((nf = allocarr(&vals[nr], line, linesize)) == 0) - errx(1, "no fields in input"); - data = line; - for (i = 0; i < nf; i++) { - if (!scannextval(&data, &val)) - errx(1, "could not parse line %ld, field %ld", nr + 1, i + 1); - vals[nr][i] = val; - } - nr++; - } + nr = fscanmatrix(stdin, &vals, &nf); + for (i = 0; i < nf; i++) { for (j = 0; j < nr; j++) { printf("%.17g", vals[j][i]); @@ -39,7 +25,6 @@ main(void) puts(""); } - free(line); for (i = 0; i < nr; i++) free(vals[i]); free(vals); diff --git a/util.c b/util.c @@ -43,3 +43,32 @@ printarr(double *arr, size_t len) } puts(""); } + +size_t +fscanmatrix(FILE *stream, double ***arr, size_t *nf) +{ + size_t i, nr = 0, linesize = 0; + char *line = NULL, *data = NULL; + double val; + + *arr = calloc(1, sizeof(double *)); + + while (getline(&line, &linesize, stream) > 0) { + if (nr > 0) + if (!(*arr = xreallocarray(*arr, nr + 1, sizeof(double *)))) + err(1, "reallocarray"); + if ((*nf = allocarr(&(*arr)[nr], line, linesize)) == 0) + errx(1, "no fields in input"); + data = line; + for (i = 0; i < *nf; i++) { + if (!scannextval(&data, &val)) + errx(1, "could not parse line %ld, field %ld", nr + 1, i + 1); + (*arr)[nr][i] = val; + } + nr++; + } + + free(line); + + return nr; +}+ \ No newline at end of file diff --git a/util.h b/util.h @@ -22,5 +22,6 @@ void * xreallocarray(void *m, size_t n, size_t s); size_t allocarr(double **arr, const char *str, size_t maxlen); int scannextval(char **str, double *val); void printarr(double *arr, size_t len); +size_t fscanmatrix(FILE *stream, double ***arr, size_t *nf); #endif