-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprimalnn.h
104 lines (86 loc) · 2.4 KB
/
primalnn.h
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
#include <stddef.h>
#include <stdio.h>
#include <time.h>
#ifndef PRIMALNN_H_
#define PRIMALNN_H_
#ifndef PRIMALNN_MALLOC
#include <stdlib.h>
#define PRIMALNN_MALLOC malloc
#endif // PRIMALNN_MALLOC
#ifndef PRIMALNN_ASSERT
#include <assert.h>
#define PRIMALNN_ASSERT assert
#endif // PRIMALNN_ASSERT
typedef struct {
size_t rows;
size_t cols;
float *es;
} Matrix;
#define MATRIX_AT(a, i, j) (a).es[(i) * (a).cols + (j)]
float rand_float(void);
Matrix matrix_alloc(size_t rows, size_t cols);
void matrix_dot(Matrix c, Matrix a, Matrix b);
void matrix_sum(Matrix c, Matrix a);
void matrix_print(Matrix a);
void matrix_rand(Matrix a, float low, float high);
void matrix_fill(Matrix a, float x);
#endif // PRIMALNN_H
#ifdef PRIMALNN_IMPLEMENTATION
float rand_float(void) {
return (float)rand() / (float)RAND_MAX;
}
Matrix matrix_alloc(size_t rows, size_t cols){
Matrix m;
m.rows = rows;
m.cols = cols;
m.es = PRIMALNN_MALLOC(sizeof(*m.es) * rows * cols);
PRIMALNN_ASSERT(m.es != NULL);
return m;
}
void matrix_dot(Matrix c, Matrix a, Matrix b){
PRIMALNN_ASSERT(a.cols == b.rows);
size_t n = a.cols;
PRIMALNN_ASSERT(c.rows == a.rows);
PRIMALNN_ASSERT(c.cols == b.cols);
for (size_t i = 0; i < c.rows; i++) {
for (size_t j = 0; j < c.cols; j++) {
MATRIX_AT(c, i, j) = 0;
for (size_t k = 0; k < n; k++) {
MATRIX_AT(c, i, j) += MATRIX_AT(a, i, k) * MATRIX_AT(b, j, k);
}
}
}
}
void matrix_sum(Matrix c, Matrix a) {
PRIMALNN_ASSERT(c.rows == a.rows);
PRIMALNN_ASSERT(c.cols == a.cols);
for (size_t i = 0; i < c.rows; i++) {
for (size_t j = 0; j < c.cols; j++) {
MATRIX_AT(c, i, j) += MATRIX_AT(a, i, j);
}
}
}
void matrix_print(Matrix a) {
for (size_t i = 0; i < a.rows; i++) {
for (size_t j = 0; j < a.cols; j++) {
printf("%f ", MATRIX_AT(a, i, j));
}
printf("\n");
}
}
void matrix_rand(Matrix a, float low, float high) {
srand(time(0));
for (size_t i = 0; i < a.rows; i++) {
for (size_t j = 0; j < a.cols; j++) {
MATRIX_AT(a, i, j) = rand_float() * (high - low) + low;
}
}
}
void matrix_fill(Matrix a, float x) {
for (size_t i = 0; i < a.rows; i++) {
for (size_t j = 0; j < a.cols; j++) {
MATRIX_AT(a, i, j) = x;
}
}
}
#endif // PRIMALNN_IMPLEMENTATION