From: yu.dongliang Date: Fri, 20 Nov 2020 03:45:51 +0000 (+0800) Subject: 1 X-Git-Url: http://baseworks.info/?a=commitdiff_plain;h=82191e3d5fcbc453e4c144f23c3f5b8250be42fc;p=mat.git 1 --- diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..92222ef --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +all: + gcc -g -O3 mat.c diff --git a/mat.c b/mat.c index 41970a6..f82a3f7 100644 --- a/mat.c +++ b/mat.c @@ -2,6 +2,7 @@ #include"stdlib.h" #include"stdint.h" #include"string.h" +#include"time.h" #include"assert.h" typedef struct buf_s buf_t; @@ -65,14 +66,52 @@ void mat_free(mat_t* m) } } -void mat_mul(mat_t* m, mat_t* m0, mat_t* m1) +void mat_add(mat_t* m, mat_t* m0, mat_t* m1) +{ + assert(m0->n == m1->n); + assert(m->n == m0->n); + + int i; + int j; + int n = m->n; + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + + int ij0 = (i + m0->i) * m0->b->n + (j + m0->j); + int ij1 = (i + m1->i) * m1->b->n + (j + m1->j); + int ij = (i + m->i) * m->b->n + (j + m->j); + + m->b->data[ij] = m0->b->data[ij0] + m1->b->data[ij1]; + } + } +} + +void mat_sub(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 n = m->n; + + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) { + + int ij0 = (i + m0->i) * m0->b->n + (j + m0->j); + int ij1 = (i + m1->i) * m1->b->n + (j + m1->j); + int ij = (i + m->i) * m->b->n + (j + m->j); + + m->b->data[ij] = m0->b->data[ij0] - m1->b->data[ij1]; + } + } +} + +void mat_mul(mat_t* m, mat_t* m0, mat_t* m1) +{ + assert(m0->n == m1->n); + assert(m->n == m0->n); int i; int j; @@ -98,6 +137,23 @@ void mat_mul(mat_t* m, mat_t* m0, mat_t* m1) } } +void mat_fill(mat_t* m) +{ + assert(m && m->b); + + int i; + int j; + + 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); + + m->b->data[ij] = rand() % 10; + } + } +} + void mat_print(mat_t* m) { assert(m && m->b); @@ -120,16 +176,23 @@ void mat_print(mat_t* m) printf("\n"); } -int main() +int main(int argc, char* argv[]) { - int a[4] = {1, 2, 3, 4}; + if (argc < 2) { + printf("argc: %d, < 2\n", argc); + return -1; + } - 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); + int n = atoi(argv[1]); - memcpy(m0->b->data, a, sizeof(int) * 4); - memcpy(m1->b->data, a, sizeof(int) * 4); + srand(time(NULL)); + + mat_t* m0 = mat_alloc(0, 0, n, NULL); + mat_t* m1 = mat_alloc(0, 0, n, NULL); + mat_t* m = mat_alloc(0, 0, n, NULL); + + mat_fill(m0); + mat_fill(m1); mat_mul(m, m0, m1); @@ -139,17 +202,3 @@ int main() return 0; } - - - - - - - - - - - - - -