Main Content

Generate Code for coneprog

This example shows how to generate C code for coneprog.

Cone Programming Problem and MATLAB® Solution

The problem uses three second-order cone constraints.

A = diag([1,2,0]);
b = zeros(3,1);
d = [0;0;1];
gamma = -1;
socConstraints(3) = secondordercone(A,b,d,gamma);

A = diag([3,0,1]);
d = [0;1;0];
socConstraints(2) = secondordercone(A,b,d,gamma);

A = diag([0;1/2;1/2]);
d = [1;0;0];
socConstraints(1) = secondordercone(A,b,d,gamma);

Create the linear objective function vector.

f = [-1;-2;-4];

Solve the problem by using the coneprog function.

[x,fval] = coneprog(f,socConstraints)
Optimal solution found.
x = 3×1

    0.4238
    1.6477
    2.3225

fval = -13.0089

Generate Code for Cone Programming Problem

To solve the same problem using code generation, create a function that accepts f as an argument, and otherwise uses the same cone constraints. For code generation, you must pass multiple cone constraints in a cell array, not as a vector of cone constraint objects. Create a function file named solvecone.m on your MATLAB path containing the following code.

function [xsol,fnval] = solvecone(f)

A = diag([1,2,0]);
b = zeros(3,1);
d = [0;0;1];
gamma = -1;
socConstraint1 = secondordercone(A,b,d,gamma);

A = diag([3,0,1]);
d = [0;1;0];
socConstraint2 = secondordercone(A,b,d,gamma);

A = diag([0;1/2;1/2]);
d = [1;0;0];
socConstraint3 = secondordercone(A,b,d,gamma);

socConstraints = {socConstraint1,socConstraint2,socConstraint3};
[xsol,fnval] = coneprog(f,socConstraints);
end

Call codegen to generate C code. codegen creates a file named solvecone_mex.

codegen -config:mex -args {f} solvecone
Code generation successful.

Run the generated code using the same f vector as before.

[xsol,fnval] = solvecone_mex(f)
xsol = 3×1

    0.4238
    1.6477
    2.3225

fnval = -13.0089

The generated code returns the same solution to display precision.

See Also

| | (MATLAB Coder)

Related Topics