#ifndef INCLUDED_C_MATRIX_H #define INCLUDED_C_MATRIX_H #ifndef INCLUDED_C_ARRAY_H #include #endif /*INCLUDED_C_ARRAY_H*/ /* ------------------------------------------------------------------------------------------------------------------ */ /* */ // “主元全为0”而触发矩阵奇异错误 #define C_ERR_SINGULAR C_ERR_FAIL /* ------------------------------------------------------------------------------------------------------------------ */ /* */ typedef struct { c_Array_t* array; // 内部封装的一维泛型数组 c_size_t rows; // 矩阵行数 c_size_t cols; // 矩阵列数 }c_Matrix_t; // 泛型数学算子包 typedef struct { void (*zero)(void* out); // 设为 0 void (*one)(void* out); // 设为 1 void (*add)(const void* a, const void* b, void* out); // out = a + b void (*sub)(const void* a, const void* b, void* out); // out = a - b void (*mul)(const void* a, const void* b, void* out); // out = a * b void (*div)(const void* a, const void* b, void* out); // out = a / b int (*is_zero)(const void* a); // 判断是否为 0 (或接近 0) int (*compare_abs)(const void* a, const void* b); // 绝对值比较:|a| > |b| 返回 1, 否则返回 0 } c_MatrixOps_t; /* ------------------------------------------------------------------------------------------------------------------ */ /* */ c_err_t c_Matrix_Init(c_Matrix_t* self, c_size_t rows, c_size_t cols, c_size_t element_size); void c_Matrix_Destroy(c_Matrix_t* self); c_size_t c_Matrix_ElementSize(c_Matrix_t* self); c_err_t c_Matrix_Get(c_Matrix_t* self, c_size_t row, c_size_t col, void** value); c_err_t c_Matrix_Put(c_Matrix_t* self, c_size_t row, c_size_t col, void* value); /* ------------------------------------------------------------------------------------------------------------------ */ /* float 运算 举例 void float_matmul_callback(const void* a, const void* b, void** c) { float val_a = *(const float*)a; float val_b = *(const float*)b; // 1. 拿到外部矩阵 C[i][j] 的真实内存地址 float* dest_cell = *(float**)c; // 2. 严格执行乘加(+=) *dest_cell += val_a * val_b; } */ c_err_t c_Matrix_Multiply(const c_Matrix_t* A, const c_Matrix_t* B, c_Matrix_t* C, void (*multiply)(const void* a, const void* b, void** c)) ; c_err_t c_Matrix_TransposeTo(c_Matrix_t* src, c_Matrix_t* dst); c_err_t c_Matrix_InPlaceTranspose(c_Matrix_t* self); /** * @brief 计算方阵的行列式 * @param self 矩阵指针 * @param ops 用户注册的泛型数学算子包 * @param out_det 存储计算结果的内存指针(外部分配) * @return c_err_t 成功返回 C_SUCCESS,非方阵返回 C_ERR_PARAM */ c_err_t c_Matrix_Determinant(const c_Matrix_t* self, const c_MatrixOps_t* ops, void* out_det); /** * @brief 使用高斯消元法求解线性方程组 Ax = b * @param A NxN 的系数矩阵指针 * @param b Nx1 的常数项向量矩阵指针 * @param x Nx1 的解向量矩阵指针(外部分配好内存) * @param ops 用户注册的泛型数学算子包 * @return c_err_t 成功返回 C_SUCCESS,维度不匹配返回 C_ERR_PARAM,矩阵奇异返回 C_ERR_SINGULAR */ c_err_t c_Matrix_Solve(const c_Matrix_t* A, const c_Matrix_t* b, c_Matrix_t* x, const c_MatrixOps_t* ops); #endif /*INCLUDED_C_MATRIX_H*/