Hi Anup,
When dealing with optimization problems in MATLAB, especially with constraints that depend on calculations within a loop, the key is to encapsulate your loop and any dependent calculations within a function that can be passed to the optimization solver as a constraint. MATLAB's optimization toolbox solvers, such as "fmincon", allow you to define both equality and inequality constraints through function handles that return the values of those constraints.
Here is a simple example where we aim to minimize a quadratic objective function subject to a constraint that involves a sum calculated in a loop:
- Set up and call the optimization solver.
options = optimoptions('fmincon', 'Display', 'iter', 'Algorithm', 'sqp');
[x, fval] = fmincon(@objectiveFunction, initialGuess, A, b, Aeq, beq, lb, ub, @constraintFunction, options);
Iter Func-count Fval Feasibility Step Length Norm of First-order
step optimality
0 3 0.000000e+00 4.000e+02 1.000e+00 0.000e+00 1.490e-08
1 6 3.200000e+02 0.000e+00 1.000e+00 1.789e+01 1.600e+01
2 9 3.200000e+02 5.684e-14 1.000e+00 4.553e-07 5.638e-07
Local minimum found that satisfies the constraints.
Optimization completed because the objective function is non-decreasing in
feasible directions, to within the value of the optimality tolerance,
and constraints are satisfied to within the value of the constraint tolerance.
disp(['Optimized a: ', num2str(x(1))]);
disp(['Optimized b: ', num2str(x(2))]);
disp(['Minimum objective function value: ', num2str(fval)]);
Minimum objective function value: 320
- Create the objective function "objectiveFunction" (e.g., ):
function obj = objectiveFunction(x)
- Create the constraint function "constraintFunction" (The constraint will be that the sum of over iterations is greater than or equal to ):
function [c, ceq] = constraintFunction(x)
sumCalculation = sumCalculation + (a + 2*b);
c = 400 - sumCalculation;
This example demonstrates how to set up and solve a constrained optimization problem in MATLAB, where the constraint involves calculations that are represented by a loop.
For more information about the "fmilncon" function, refer to this documentation link:
For understanding the use-cases of anonymous functions, refer to this resource:
I hope this helps!