-
Notifications
You must be signed in to change notification settings - Fork 2
/
mat.c
128 lines (105 loc) · 2.47 KB
/
mat.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/**
* Simple matrix implementation.
*
* @blackball
*/
#include "mat.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct mat_t*
mat_new(int r, int c) {
struct mat_t *m = malloc(sizeof(*m));
m->data = malloc(sizeof(double) * r * c);
m->rows = r;
m->cols = c;
return m;
}
void
mat_free(struct mat_t **m) {
if (m && (*m)) {
free( (*m)->data );
free( *m );
*m = NULL;
}
}
void
mat_set(struct mat_t *m, double v) {
if (m) {
int i,j;
for (i = 0; i < m->rows; ++i) {
for (j = 0; j < m->cols; ++j) {
m->data[i * m->cols + j] = v;
}
}
}
}
double
mat_sum_col(const struct mat_t *m, int col) {
double sum = .0;
int i = 0;
assert(col < m->cols);
for (; i < m->rows; ++i) {
sum += m->data[i * m->cols + col];
}
return sum;
}
double
mat_sum_row(const struct mat_t *m, int row) {
double sum = .0;
int i = 0;
assert(row < m->rows);
for (; i < m->cols; ++i) {
sum += m->data[ row * m->cols + i];
}
return sum;
}
struct mat_t*
mat_load(const char *nn) {
FILE *fn = NULL;
struct mat_t *m = NULL;
int rows = 0, cols = 0, counter;
if (nn == NULL) {
goto _DOOR;
}
fn = fopen(nn, "r");
if (fn == NULL) {
goto _DOOR;
}
if (2 != fscanf(fn, "%d%d", &rows, &cols)) {
goto _DOOR;
}
if (rows <= 0 || cols <= 0) {
goto _DOOR;
}
m = mat_new(rows, cols);
if (m == NULL) {
goto _DOOR;
}
counter = 0;
while (1 == fscanf(fn, "%lf", m->data + counter) && (counter < cols * rows)) {
++ counter;
}
if ( counter != rows * cols ) {
mat_free(&m);
goto _DOOR;
}
_DOOR:
if (fn) {
fclose(fn);
}
return m;
}
void
mat_print(const struct mat_t *m) {
int i, j;
if (!m) {
return ;
}
for (i = 0; i < m->rows; ++i) {
for (j = 0; j < m->cols; ++j) {
printf("%lf ", MAT_AT(m, i, j));
}
printf("\n");
}
}