How to Solve Constrained Optimization Problems Using Matlab

Hello everyone and welcome!

In this post, I’m going to show you a simple but very effective method to solve many constrained optimization problems using Matlab. This optimization method is based on fmincon solver and multi-start procedure.

Here are details of the benchmark function.

Let’s see how this optimization algorithm works.

For more videos like this, check my YouTube channel here.

Matlab code

objective_function.m

function Output = objective_function(Input)
x = Input(1);
y = Input(2);
Output = -(cos((x-0.1)*y))^2 -x*sin(3*x+y);

nonlinear_constraint.m

function [C Ceq] = nonlinear_constraint(Input)
x = Input(1);
y = Input(2);

t = atan2(x,y);
C = x^2 + y^2 -(2*cos(t)-(1/2)*cos(2*t) - ...
    (1/4)*cos(3*t) -(1/8)*cos(4*t))^2 - (2*sin(t))^2; % inequality constraint 
Ceq = [];  % no equality constraint in this problem

fminconsolver.m

function [x,fval,exitflag,output,lambda,grad,hessian] = fminconsolver(x0,lb,ub)
options = optimoptions('fmincon');
options = optimoptions(options,'Display', 'off');
options = optimoptions(options,'PlotFcn', {  @optimplotfval @optimplotconstrviolation });
[x,fval,exitflag,output,lambda,grad,hessian] = ...
fmincon(@objective_function,x0,[],[],[],[],lb,ub,@nonlinear_constraint,options);

main_code.m

clc
clear all
close all
%--------------------------------------------------------------------------
% customization: lower bound lb = [1xn], and upper bound lb = [1xn]
lb = [-2.25 -2.5];
ub = [2.5 1.75];
%--------------------------------------------------------------------------
n = 10; % number of runs

[x y]=size(lb);
S=zeros(n,y);
R=zeros(n,1);
% multi-start optimization solver
for j=1:n
    for i = 1:y
        x0(i)=lb(i) + (ub(i)-lb(i))*rand; % generate initial solution
    end
    [x,fval,exitflag,output,lambda,grad,hessian] = fminconsolver(x0,lb,ub);
    S(j,:)=x;
    R(j,1)=fval;
end
[x1 y1]=find(R == min(R));
objective_function_value = R(min(x1),1)
optimal_solution = S(min(x1),:)

P/s: If you find the post useful, share it to remember and to help other people as well.

3 Replies to “How to Solve Constrained Optimization Problems Using Matlab”

Leave a Reply

Your email address will not be published. Required fields are marked *