-
Notifications
You must be signed in to change notification settings - Fork 0
/
smat.c
94 lines (79 loc) · 1.68 KB
/
smat.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Array allocation/deallocation helpers.
* NOTE: matrices are allocated row-by-row in contiguous virtual address space.
*/
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "smat.h"
void free_2d_double(double **matrix)
{
if (matrix == NULL)
return;
if (matrix[0])
free(matrix[0]);
free(matrix);
}
/*
void *calloc_2d_double(size_t rows, size_t cols)
{
double *flat;
double **mem;
int i;
flat = calloc(rows, cols * sizeof(double));
if (flat == NULL) {
fprintf(stderr, "%s: Error allocating %Zu bytes: ",
__func__, rows * cols * sizeof(double));
perror(NULL);
exit(EXIT_FAILURE);
}
mem = malloc(rows * sizeof(double *));
if (mem == NULL) {
perror("calloc_2d_double");
exit(EXIT_FAILURE);
}
for (i = 0; i < rows; i++)
mem[i] = flat + i * cols;
return mem;
}
*/
/* Print array in an octave-friendly format */
void smat_printf(const char *title, const struct smat *mat)
{
int is_scalar = mat->rows == 1 && mat->cols == 1;
int i, j;
if (title)
printf("# name: %s\n", title);
if (is_scalar) {
printf("# type: scalar\n");
} else {
printf("# type: matrix\n");
printf("# rows: %u\n", mat->rows);
printf("# columns: %u\n", mat->cols);
}
for (i = 0; i < mat->rows; i++) {
for (j = 0; j < mat->cols; j++)
printf(" %.17e", mat->data[i][j]);
printf("\n");
}
}
void smat_free(struct smat *mat)
{
if (mat == NULL)
return;
free_2d_double(mat->data);
free(mat);
}
struct smat *smat_calloc(size_t rows, size_t cols)
{
struct smat *m;
m = malloc(sizeof(struct smat));
if (m == NULL) {
perror("calloc_smat");
exit(EXIT_FAILURE);
}
m->rows = rows;
m->cols = cols;
m->data = (double **)calloc_2d_double(rows, cols);
return m;
}