From 25ef7b1cb1cd6f6257baf1087e3669b03bc213fd Mon Sep 17 00:00:00 2001 From: "yu.dongliang" Date: Fri, 20 Nov 2020 11:29:45 +0800 Subject: [PATCH 1/1] mat --- mat.c | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 mat.c diff --git a/mat.c b/mat.c new file mode 100644 index 0000000..41970a6 --- /dev/null +++ b/mat.c @@ -0,0 +1,155 @@ +#include"stdio.h" +#include"stdlib.h" +#include"stdint.h" +#include"string.h" +#include"assert.h" + +typedef struct buf_s buf_t; +typedef struct mat_s mat_t; + +struct buf_s +{ + int refs; + int n; + int data[0]; +}; + +struct mat_s +{ + int i; + int j; + int n; + buf_t* b; +}; + +buf_t* buf_alloc(int n) +{ + assert(n > 0); + + buf_t* b = malloc(sizeof(buf_t) + sizeof(int) * n * n); + assert(b); + + b->refs = 1; + b->n = n; + return b; +} + +void buf_free(buf_t* b) +{ + if (b && 0 == --b->refs) + free(b); +} + +mat_t* mat_alloc(int i, int j, int n, buf_t* b) +{ + mat_t* m = malloc(sizeof(mat_t)); + assert(m); + + m->i = i; + m->j = j; + m->n = n; + + if (!b) { + b = buf_alloc(n); + assert(b); + } + m->b = b; + return m; +} + +void mat_free(mat_t* m) +{ + if (m) { + buf_free(m->b); + free(m); + } +} + +void mat_mul(mat_t* m, mat_t* m0, mat_t* m1) +{ + assert(m0->n == m1->n); + assert(m->n == m0->n); + + assert(m0->b); + assert(m1->b); + assert(m->b); + + int i; + int j; + int k; + int n = m->n; + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + + int sum = 0; + for (k = 0; k < n; k++) { + + int ik = (i + m0->i) * m0->b->n + (k + m0->j); + int kj = (k + m1->i) * m1->b->n + (j + m1->j); + + sum += m0->b->data[ik] * m1->b->data[kj]; + } + + int ij = (i + m->i) * m->b->n + (j + m->j); + + m->b->data[ij] = sum; + } + } +} + +void mat_print(mat_t* m) +{ + assert(m && m->b); + + int i; + int j; + + printf("m: %p, i: %d, j: %d, n: %d, m->b->n: %d, m->b: %p\n", + m, m->i, m->j, m->n, m->b->n, m->b); + + for (i = 0; i < m->n; i++) { + for (j = 0; j < m->n; j++) { + + int ij = (i + m->i) * m->b->n + (j + m->j); + + printf("%8d ", m->b->data[ij]); + } + printf("\n"); + } + printf("\n"); +} + +int main() +{ + int a[4] = {1, 2, 3, 4}; + + mat_t* m0 = mat_alloc(0, 0, 2, NULL); + mat_t* m1 = mat_alloc(0, 0, 2, NULL); + mat_t* m = mat_alloc(0, 0, 2, NULL); + + memcpy(m0->b->data, a, sizeof(int) * 4); + memcpy(m1->b->data, a, sizeof(int) * 4); + + mat_mul(m, m0, m1); + + mat_print(m0); + mat_print(m1); + mat_print(m); + return 0; +} + + + + + + + + + + + + + + + -- 2.25.1