为 linprog 生成代码
此示例说明如何为 linprog 优化求解器生成代码。代码生成需要 MATLAB Coder™ 许可证。有关代码生成要求的详细信息,请参阅 linprog 背景下的代码生成。
问题
问题是求解一个具有以下线性不等式约束矩阵 A 和 b 以及线性等式约束矩阵 Aeq 和 beq 的二维线性规划问题。
A = [1 1
1 1/4
1 -1
-1/4 -1
-1 -1
-1 1];
b = [2 1 2 1 -1 2];
Aeq = [1 1/4];
beq = 1/2;设置以下边界:
lb = [-1,-0.5]; ub = [1.5,1.25];
使用目标函数 。
f = [-1 -1/3];
设置代码生成
创建一个名为 test_linprog.m 的文件,其中包含创建问题和约束的代码。该文件必须设置使用 "interior-point" 算法的选项。
function [x,fval,exitflag,output] = test_linprog A = [1 1 1 1/4 1 -1 -1/4 -1 -1 -1 -1 1]; b = [2 1 2 1 -1 2]; Aeq = [1 1/4]; beq = 1/2; f = [-1 -1/3]; lb = [-1,-0.5]; ub = [1.5,1.25]; opts = optimoptions("linprog",Algorithm="interior-point"); [x,fval,exitflag,output] = linprog(f,A,b,Aeq,beq,lb,ub,opts); end
为 test_linprog 文件生成代码。
codegen -config:mex test_linprog
Code generation successful.
一段时间后,codegen 会创建一个名为 test_linprog_mex.mexw64 的 MEX 文件(文件扩展名因系统而异)。运行生成的 C 代码。
[x,fval,exitflag,output] = test_linprog_mex
x = 2×1
0.1875
1.2500
fval = -0.6042
exitflag = 1
output = struct with fields:
algorithm: 'interior-point'
constrviolation: 3.5682e-07
firstorderopt: 3.6989e-06
iterations: 4
1 的退出标志表明代码创建了一个可靠的解。该代码只需四次迭代即可得出解,对于如此简单的问题而言,这并不奇怪。
另请参阅
linprog | codegen (MATLAB Coder) | optimoptions