Generate Code for linprog - MATLAB & Simulink (original) (raw)

This example shows how to generate code for the linprog optimization solver. Code generation requires a MATLAB Coder™ license. For details about code generation requirements, see Code Generation for linprog Background.

Problem

The problem is to solve a 2-D linear program with the following linear inequality constraint matrices A and b and linear equality constraint matrices Aeq and 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;

Set these bounds:

-1≤x(1)≤1.5-0.5≤x(2)≤1.25.

lb = [-1,-0.5]; ub = [1.5,1.25];

Use the objective function -x(1)-x(2)/3.

Set Up Code Generation

Create a file named test_linprog.m containing code that creates the problem and constraints. The file must set options to use the "interior-point" algorithm.

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

Generate code for the test_linprog file.

codegen -config:mex test_linprog

Code generation successful.

After some time, codegen creates a MEX file named test_linprog_mex.mexw64 (the file extension varies, depending on your system). Run the resulting C code.

[x,fval,exitflag,output] = test_linprog_mex

output = struct with fields: algorithm: 'interior-point' constrviolation: 3.5682e-07 firstorderopt: 3.6989e-06 iterations: 4

The exit flag of 1 indicates that the code creates a reliable solution. The code takes only four iterations to reach the solution, which is not surprising for such a small problem.

See Also

linprog | codegen (MATLAB Coder) | optimoptions

Topics