# 2017q1 Homework5(matrix) contributed by <`hugikun999`> ## matrix ### Fix hard code 在 `matrix_native.h` 所提供的運算全部都受限於 4x4 矩陣,更改 Matrix 結構的成員,使其得以存入不同數量的資料,亦修改運算實作以達到目標。 ```C typedef struct { int row, col; float *values; } Matrix; ``` ```C static void assign(Matrix *thiz, int row, int col, float *value) { thiz->row = row; thiz->col = col; thiz->values = (float *)malloc(row * col * sizeof(float)); for (int i = 0; i < col; i++) for (int j = 0; j < row; j++) *(thiz->values + i * row + j) = *(value + i * row + j); } ``` ### Fix error hanlding ```C bool mul(Matrix *dst, const Matrix *l, const Matrix *r) { for (int i = 0; i < COL(l); i++) for (int j = 0; j < ROW(r); j++) for (int k = 0; k < ROW(l); k++) *(dst->values + i * COL(l) + j) += *(l->values + i * COL(l) + k) * *(r->values + k * COL(l) + j); return true; } ``` ### Create random martix 這邊利用 `getrandom()` 來取得隨機的變數以當成矩陣內所存的資料,不過將實際的值印出來的時候,發現值不是極大、極小不然就是 `0`,感覺是資料 align 時沒有按照 4 bits。 ```C Matrix *create_new(int row, int col) { Matrix *new_mat = (Matrix *) malloc(sizeof(Matrix)); new_mat->row = row; new_mat->col = col; new_mat->values = (float *) malloc(sizeof(float) * row * col); if (!syscall(SYS_getrandom, new_mat->values, sizeof(float) * row * col, GRND_NONBLOCK)) { perror("error create"); return NULL; } return new_mat; } ``` 改用 `align_alloc()` 分配位置也是一樣的結果,如此應該就不會是資料 align 的問題了。 ```C new_mat->values = (float *) aligned_alloc(sizeof(float), sizeof(float) * row * col); ``` :::danger 你用 man page 提供的程式驗證過了嗎? --jserv :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up