用 C 語言實作矩陣運算的 Function
業界上常用的 Matlab 軟體,因為本身就是為了做數學運算而設計,所以在數值分析和處理方面非常快速好用,但是在 C 語言就中沒有那些好用的指令和數學函式庫了,得自己打造所有的運算流程和架構。舉例來說,使用 C 語言來做矩陣運算,程式開發者都是先『指定行列數量』建立一個陣列,再『指定行列數量』去對內部的值,一一做處理或高斯消去解方程式,這比起 Matlab 中用兩行就可以搞定一切運算,可說易用性相差甚遠。 所以就想到,要是我們能設計出一套好用的 C 語言矩陣函式庫,是否就可以省下這些重覆設計矩陣運算流程的時間?於是可以做一些實作,來完成這個任務。 基本的矩陣資料結構: typedef struct { int rows; int cols; int total; double *table; } Matrix; 其中定義了幾個基本的 functions 做矩陣的處理: 建立矩陣: Matrix *matrix_create(int rows, int cols) 矩陣最佳化: Matrix *matrix_optimize(Matrix *matrix) 解矩陣的方程式: Matrix *matrix_solution(Matrix *matrix) 顯示並列出矩陣內容: void matrix_print(Matrix *matrix) 清空矩陣: void matrix_clear(Matrix *matrix) 函式的程式碼: void matrix_clear(Matrix *matrix) { int i, j; double *ptr; /* initializing matrix */ ptr = matrix->table; for (i=0;i<matrix->total;i++) *(ptr++) = 0; } Matrix *matrix_create(int rows, int cols) { Matrix *matrix; /* allocate */ matrix = (Matrix *)malloc(sizeof(Matrix)); matrix->rows = rows; matrix->cols = col...