三亩地 三亩地SAN MU DI · CODE DIARY
ARTICLE DETAIL

日记详情

真实记录编程学习的某一天,欢迎挑你感兴趣的翻一翻。

矩阵运算库 C语言 (Matrix_hub)

矩阵运算库 C语言 (Matrix_hub)

Matrix Hub v2.0

项目位置GitHub - Amoiensis/Matrix_hub: A lib of Matrix operation for C language. (矩阵运算库--C语言) · GitHub

语言: 中文 / English / 日本語

Matrix Hub v2.0 是一个轻量级矩阵计算与优化求解工具集,核心目标是在较小代码体积下提供可嵌入、可脚本化、可命令行调用的矩阵计算能力。项目采用 C 语言实现,适合嵌入式部署、轻量应用、小规模工程计算,以及在此基础上的二次开发,例如控制算法、二次优化和工程计算原型。

项目包含三种使用形态:矩阵运算 C 头文件库、类 Matlab 的.m脚本/交互式计算器,以及可作为插件或独立程序使用的轻量 LP/MIP 求解器。预编译求解器与交互式计算器的体积保持在约 100KB 级别,便于部署和集成。

直接下载使用

当前提供 Apple Silicon macOS 和 Windows x64 的预编译版本,下载解压后即可直接使用。其他平台可以从源码编译,或通过邮件联系作者协助。

平台下载内容
macOS Apple SiliconMatrixHub-v2.0-macos-arm64.zipCLI 脚本计算器、LP/MIP Solver、help 文档和示例
Windows x64MatrixHub-v2.0-windows-x64.zipCLI 脚本计算器、LP/MIP Solver、help 文档和示例

项目信息

项目信息
ProjectGitHub - Amoiensis/Matrix_hub: A lib of Matrix operation for C language. (矩阵运算库--C语言) · GitHub
AuthorSebin (Xiping.Yu)
EmailAmoiensis@outlook.com

欢迎通过邮件交流使用问题、建议和工程应用场景。

三种用法

用法目标用户入口
C 头文件库在 C/C++ 项目中做矩阵运算和二次开发,如控制算法、优化算法原型include/matrix.h,include/solver_plugin/*.h
交互式脚本计算器像 Matlab.m文件一样运行脚本,也支持>>逐行交互build/Matrix_Hub_v2_0_cli
轻量 LP/MIP 求解器约 100KB 级求解器/插件,读取.lp文件并输出进度、gap 和结果build/Matrix_Hub_v2_0_solver

目录结构

include/ C 头文件库入口 include/solver_plugin/ Linear/LP/MIP 求解器插件 apps/ 交互式脚本计算器与轻量 LP/MIP solver 程序 examples/c_library/ C 库调用示例和独立 CMakeLists.txt examples/scripts/ MatrixHub .m 脚本示例 examples/solver/ LP/MIP 求解器用法、问题文件和转换工具 help/ 函数、命令和 solver 帮助文档

支持的运算

类别脚本/CLI 写法C API / 插件说明
矩阵创建A = [1 2; 3 4]Matrix_gen从连续数据生成矩阵
矩阵复制-Matrix_copy深拷贝矩阵
内存释放-M_free释放 MatrixHub 创建的矩阵
显示输出print(A)M_print打印矩阵
单位矩阵eye(n)M_I生成单位矩阵
零矩阵zeros(m,n)M_Zeros生成全零矩阵
一矩阵ones(m,n)M_Ones生成全一矩阵
Hilbert 矩阵hilbert(n)Hilbert常用于数值稳定性测试的病态矩阵
范围向量[2:6],[1:1.2:100]-支持 start:end 和 start:step:end
加减法A + B,A - BM_add_sub矩阵加减
矩阵乘法A * BM_mul标准矩阵乘法
标量乘除2*A,A/3M_numul标量与矩阵混合计算
对应元素乘除pmul(A,B),pdiv(A,B)M_pmuldivHadamard 乘除
转置A',transpose(A)M_T矩阵转置
求逆inv(A)M_Inverse适合小规模矩阵计算
伪逆pinv(A)M_pinv默认逐步改进为更稳定风格
行列式det(A)M_det方阵行列式
tr(A),trace(A)M_tr方阵对角线求和
范数norm(A)M_norm支持常用矩阵/向量范数
条件数cond(A)M_cond基础条件数估计
rank(A)M_rank矩阵秩
绝对值abs(A)M_abs元素绝对值
求和sum(A)M_sum元素求和
最小/最大min(A),max(A)M_min,M_max元素最值
对角处理diag(A)M_Dia_Inv, related helpers对角提取/对角矩阵相关能力
矩阵尺寸shape(A),size(A)A->row,A->column返回[rows columns]
单元素索引A(1,2)direct data access脚本索引从 1 开始
切片A[:,1],A[1:2,2:3]M_Cut,M_Sample行列截取和采样
查找find(A)M_find查找满足条件的元素位置
逻辑比较A == B,A < BM_logic,M_logic_equal标量/矩阵逻辑判断
行列交换swap(A,...)M_Swap行或列交换
初等变换-M_E_trans,Etrans_2_Matrix,Etrans_4_Inverse基础初等变换
上三角化[T,U] = uptri(A)M_Uptri_保留初等变换实现
下三角化[T,L] = lowtri(A)M_Lowtri_保留初等变换实现
对角化[Tl,D,Tr] = diatri(A)M_Diatri_基础对角化过程
Householder[H,y] = householder(x)householder,M_householder正交变换基础
Hessenberg[Q,H] = hessenberg(A)M_householderbased pathHessenberg 变换
QR 分解[Q,R] = qr(A)M_QRHouseholder 风格 QR,支持非方阵
SVD 分解[U,S,V] = svd(A)M_SVD小规模 SVD 分解
特征值/向量[D,E] = eigen(A),eig(A)M_eigen,M_eigen_val特征值和特征向量
最大特征对[lambda,v] = eigen_max(A)M_eigen_max幂迭代风格最大特征值
多输出兼容别名qr_q,svd_u,eigen_veccorresponding C helpers老接口兼容,新脚本推荐多输出
循环for k = 1:3 ... end-脚本控制流
判断if/elif/else/end-脚本条件分支
变量管理vars,who,clean,del A-REPL 工作区管理
清屏和帮助clear,help qrhelp/*.txt查询命令、函数和 solver 说明
线性方程-Linear_Solve稠密高斯消元,避免显式求逆
LP 求解solver CLILP_Solver默认修订单纯形,可选内点法
MIP 求解solver CLIMIP_Solver轻量 cuts + branch-and-bound

用法 1:作为 C 库引用

Matrix Hub 仍保持头文件为主的简单使用方式。直接包含include/matrix.h,需要 solver 时再包含include/solver_plugin/*.h

#include "matrix.h" #include "solver_plugin/plugin_Linear_Solver.h" #include "solver_plugin/plugin_LP_Sover.h" #include "solver_plugin/plugin_MIP_Solver.h"

一个使用例子:

MATRIX_TYPE a_data[4] = { /* \ \ __ ___ __ _ __ __ __ \ \ / |/ /__ _/ /_____(_)_ __ / // /_ __/ / / / / /|_/ / _ `/ __/ __/ /\ \ // _ / // / _ \ / / /_/ /_/\_,_/\__/_/ /_//_\_\/_//_/\_,_/_.__/ * [INFORMATION] MATRIX_HUB AUTHOR: Xiping.Yu E-MAIL: Amoiensis@outlook.com GITHUB: https://github.com/Amoiensis/Matrix_hub DATE: 2020.02.12-2023.08.21 VERSION: 1.5.2 CASE: Matrix Operation (C) DETAILS: The demo-code for Matrix_Hub. LICENSE: Apache-2.0 */ #include <stdio.h> #include <stdlib.h> #include "matrix.h" // # include "./solver_plugin/plugin_LP_Sover.h" int main(int argc, char *argv[]) { /* [Setting Matrix]*/ // Mat_1 ... [ 具体矩阵赋值,见 demo.c ] /* [Matrix Operation]*/ // 乘法 Matrix *mat_3 = M_mul(mat_2, mat_1); M_print(mat_3); // 加减法 Matrix *mat_diff = M_add_sub(1, mat_21, 1, mat_21b); M_print(mat_diff); // 初等变换 Etrans_struct _Etrans_; _Etrans_.minuend_line = 2; _Etrans_.subtractor_line = 1; _Etrans_.scale = 2; _Etrans_.next_E_trans = NULL; _Etrans_.forward_E_trans = NULL; M_E_trans(mat_2, &_Etrans_, _ROW_); M_print(mat_2); // 单位矩阵 M_print(M_I(5)); // 初等变换to矩阵 Matrix *mat_4 = Etrans_2_Matrix(&_Etrans_, 5, _ROW_); M_print(mat_4); // 上三角变换 Uptri_struct *_Uptri_ = M_Uptri_(mat_21); M_print(_Uptri_->trans_matrix); M_print(_Uptri_->Uptri_matrix); // 下三角变换 Lowtri_struct *_Lowtri_ = M_Lowtri_(mat_21); M_print(_Lowtri_->Lowtri_matrix); M_print(_Lowtri_->trans_matrix); // 对角化 Dia_struct *_Dia_ = M_Diatri_(mat_21); M_print(_Dia_->trans_leftmatrix); M_print(_Dia_->Diatri_matrix); M_print(_Dia_->trans_rightmatrix); // 矩阵求逆 Matrix *_mat_inv = M_Inverse(mat_21); M_print(_mat_inv); // 行列交换 M_Swap(_mat_inv, 1, 2, _ROW_); M_print(_mat_inv); // 切割部分 Matrix *_mat_cut = M_Cut(_mat_inv, _END_, _END_, 2, 3); M_print(_mat_cut); // 转置 Matrix *_mat_T = M_T(_mat_inv); M_print(_mat_T); // 迹 MATRIX_TYPE _tr_mat = M_tr(_mat_inv); printf("Trace(Matrix_%x) = %.4lf\n", _mat_inv, _tr_mat); // 行列式 MATRIX_TYPE _det_mat = M_det(_mat_inv); printf("Det(Matrix_%x) = %.4lf\n", mat_21, _det_mat); // 填充 Matrix *mat_full = M_full(mat_2, 1, 1, 1, 1, 0); M_print(mat_full); M_print(mat_2); // 范数 printf("NORM_L1(mat_%x) = %lf\n",mat_b, M_norm(mat_b, 1)); printf("NORM_L2(mat_%x) = %lf\n",mat_b, M_norm(mat_b, 2)); // 秩 printf("Rank(mat_%x) = %d\n", mat_A10, M_rank(mat_A10)); printf("Rank(mat_%x) = %d\n", mat_full, M_rank(mat_full)); // Hilbert 希尔伯特矩阵 M_print(Hilbert(5)); // 条件数计算 printf("->> Condition_Value = %lf\n", M_cond(Hilbert(5),1)); // 矩阵householder变换 Matrix * M_H = M_householder(Hilbert(5)); M_print(M_H); // 矩阵特征值 + 特征向量 Matrix *target = mat_eigen_test; M_print(target); Matrix ** M_eigen_val_vec = M_eigen(target); enum{val=0, vec=1}; M_print(M_eigen_val_vec[val]); M_print(M_eigen_val_vec[vec]); // 矩阵QR分解 Matrix ** M_Q_R = M_QR(Hilbert(5)); enum{q=0, r=1}; M_print(M_Q_R[q]); M_print(M_Q_R[r]); // 矩阵 SVD 分解. Matrix ** mat_list_SVD = M_SVD(mat_1); enum{U=0, Dia=1, V=2}; M_print(mat_list_SVD[U]); M_print(mat_list_SVD[Dia]); M_print(mat_list_SVD[V]); // 矩阵求伪逆 Matrix * mat_pinv = M_pinv(mat_1, _SVD_); M_print(mat_pinv); /* [Application]*/ /* [CASE 1: LP] | min CX |s.t. AX=b,X>=0 LP: linear programming, 求解线性规划. [Note.] 需要在main文件引入 "plugin_LP_Sover.h" # include "./solver_plugin/plugin_LP_Sover.h" */ M_LP_struct* LP_result = NULL; // [LP-Case 1] enum LP_method{_Simplex=1,}; printf("*** LP-SOLVER START ***\n"); LP_result = LP_Solver(mat_A_lp, mat_B_lp,mat_C_lp, _Simplex); // 使用单纯形法解线性规划. printf("*** LP-SOLVER END ***\n"); if (LP_result != NULL){ printf("[COST]\n"); // mat_C_lp, C矩阵, 成本矩阵. M_print(LP_result->_matrix_c); printf("[BASE]\n"); // 最优解的基构成 M_print(LP_result->_matrix_base); printf("[VALUES]\n"); // 最优值 M_print(M_T(LP_result->_matrix_b)); printf("[MAT_A]\n"); // 最后的变换系数矩阵. M_print(LP_result->_matrix_A); printf("[DELTA]\n"); // 各基的delta. M_print(LP_result->_matrix_delta); printf(">> OPT-VALUES: %lf\n", LP_result->values_opt); // 求解状态. printf(">> iter-num: %d\n", LP_result->iter_num); printf(">> [Note.] Please Check is Feasible or Not.\n"); // 求解迭代次数. LP_free(LP_result); }else{ system("pause"); printf("[NO FEASIBLE.] SEARCH ALL BRANCHES.\n"); } // [ CASE 2: linear equations solver]linear equations, // 解线性方程. e.g. mat_A*x = mat_b printf("# Solver:mat_A*x = mat_b\n"); Matrix *_mat_result = M_mul(M_Inverse(mat_A10), mat_b10); M_print(_mat_result);(M_Inverse(mat_A10), mat_b10); M_print(_mat_result); /* [Others]*/ // Free Memory of Matrix, 释放矩阵内存. M_free(_mat_T); /* [Help]*/ help("help"); help("M_rank"); help("Update"); help("MatrixHub"); system("pause"); return 0; }

更完整的 C 库调用方式可以查看:examples/c_library/main.c。该示例覆盖矩阵创建、线性方程求解、LP/MIP 插件调用和内存释放等用法。

运行完整示例:

cmake -S examples/c_library -B build_c_example -DMATRIXHUB_ROOT=$PWD cmake --build build_c_example ./build_c_example/matrixhub_c_example

用法 2:交互式脚本计算器

交互模式会先显示 MatrixHub logo,然后用简洁的>>提示输入:

./build/Matrix_Hub_v2_0_cli
\ \ __ ___ __ _ __ __ __ \ \ / |/ /__ _/ /_____(_)_ __ / // /_ __/ / / / / /|_/ / _ `/ __/ __/ /\ \ // _ / // / _ \ / / /_/ /_/\_,_/\__/_/ /_//_\_\/_//_/\_,_/_.__/ MatrixHub v2.0 script mode Project: https://github.com/Amoiensis/Matrix_hub ​ >> A = [4 1 2; 1 3 0; 2 0 5] >> b = [7; 8; 9] >> x = pinv(A) * b >> residual = norm(A*x - b) >> [Q, R] = qr(A) >> vars >> help qr

脚本模式适合放在文档或课程材料里,像 Markdown 代码块一样展示一段完整计算:

A = [4 1 2; 1 3 0; 2 0 5]; b = [7; 8; 9]; x = pinv(A) * b residual = norm(A*x - b) ​ [Q, R] = qr(A); [U, S, V] = svd(A); [D, E] = eigen(A); ​ for k = 1:3 P = A + k * eye(3) end ​ if det(A) > 0 sign = 1 elif det(A) < 0 sign = -1 else sign = 0 end

运行:

./build/Matrix_Hub_v2_0_cli examples/scripts/basic.m ./build/Matrix_Hub_v2_0_cli --debug debug.txt examples/scripts/basic.m

REPL 支持左/右移动光标,上/下浏览历史输入;脚本中分号会抑制输出,--debug会把变量快照写入文本文件。

用法 3:轻量 LP/MIP 求解器

solver 模式用于读取.lp文件并求解 LP/MIP 问题。它保持约 100KB 级别的小体积,适合轻量部署和简易开发使用,也可以展示分支定界过程中的 incumbent、bound 和 gap。

./build/Matrix_Hub_v2_0_solver --help ./build/Matrix_Hub_v2_0_solver lp examples/solver/problems/ortools_mip.lp ./build/Matrix_Hub_v2_0_solver mip examples/solver/problems/ortools_mip.lp

一个带进度和结果报告的 MIP 示例:

./build/Matrix_Hub_v2_0_solver mip examples/solver/problems/gt2.lp \ --progress=25 \ --node-limit=5000 \ --time-limit=30 \ --gap-limit=0.05 \ --output-dir solver_report_store

输出会类似这样:

MatrixHub v2.0 solver mode Project: https://github.com/Amoiensis/Matrix_hub [example parser] parsed vars=188 rows=29 integer=188 [MIP] node=0 open=1 cuts=... incumbent=none lower_bound=-inf upper_bound=none gap=inf event=start [MIP] node=25 open=... cuts=... incumbent=... lower_bound=... upper_bound=... gap=... event=relax status = NODE_LIMIT (2) incumbent_status = FEASIBLE objective = ... [example report] wrote solver_report_store/gt2_mip_result.txt

常用参数:

--progress[=N] 每 N 次迭代/节点显示进度 --output-dir DIR 输出人类可读的结果报告 --time-limit SEC 最大求解时间 --gap-limit VALUE 达到 gap 后停止 --node-limit N MIP 最大节点数 --open-limit N MIP 最大 open node 数 --method bb|cut-bb B&B 或 root cuts + B&B --branch first|most 分支变量选择 --node-select dfs|best-bound --bound-mode parent|tight

examples/solver/problems/只保留小型发布样例:gt2.lportools_mip.lportools_mip_array.lplpp0033.lp。更大的 LP/MIP benchmark 不随仓库提交,下载来源见 examples/solver/README.md。

帮助

MatrixHub 的帮助分为三类:

场景使用方式
C 函数/API在 CLI 中输入help M_mulhelp M_QRhelp c_library,或直接查看help/M_mul.txtinclude/matrix.h
命令行计算器在 REPL 中输入helphelp script_modehelp script_functionshelp vars
LP/MIP solver运行./build/Matrix_Hub_v2_0_solver --help,或在 CLI 中输入help solver_mode

常用主题:

help help script_mode help script_functions help solver_mode help c_library help M_mul

主要帮助入口采用中英双语;单个函数的详细说明保存在对应的help/*.txt文件中。

构建

cmake -S . -B build cmake --build build

主要产物:

build/Matrix_Hub_v2_0_demo C 库调用示例 build/Matrix_Hub_v2_0_cli 交互式脚本计算器 build/Matrix_Hub_v2_0_solver 轻量 LP/MIP 文件求解器

维护说明

v2.0 发布树只保留当前版本源码。历史版本目录由旧 main/archive 分支保存,不再放入主开发目录。

← 返回列表