Hi Silver,
I understand that you are trying to optimize a model using the fmincon function in MATLAB to obtain three parameters (x1, x2, x3) that minimize or fit a given set of data. You have a complex script that involves global variables, data fitting using lsqnonlin, and plotting results, but your main focus seems to be on optimizing parameters for a model using fmincon.
To streamline and correct your approach, especially for the optimization part, here's a concise guide and code snippet:
- Define the Objective Function Correctly: Your objective function needs to be defined properly to be used with fmincon. This function should accept a single vector argument [x1, x2, x3] and return the scalar value to be minimized. Avoid using global variables to pass data into your objective function.
- Optimization with fmincon: Use fmincon correctly by defining constraints and the objective function in a way that MATLAB expects.
Given your scenario, here's how you can adjust the relevant parts of your script, particularly focusing on the definition of the objective function and the call to fmincon:
Objective Function (funz.m)
Create a separate file named funz.m with the following content:
function z = funz(x)
% Assuming x is a vector [x1, x2, x3]
z = 62.8*x(1) + 173.1*x(2) + 122.6*x(3) + 131.0*x(1)*x(2) + 228.2*x(1)*x(3) + 274.2*x(2)*x(3) + 1597.9*x(1)*x(2)*x(3);
end
Call to fmincon
Adjust your script to correctly call fmincon with the objective function, initial guess, bounds, and constraints:
% Initial guess, bounds, and linear equality constraints
x0 = [0.3, 0.3, 0.3]; % Initial guess
lb = [0, 0, 0]; % Lower bounds
ub = [1, 1, 1]; % Upper bounds
Aeq = [1, 1, 1]; % Linear equality constraints coefficients
beq = 1; % Linear equality constraints target value
% Objective function handle
objFun = @funz;
% Optimization
options = optimoptions('fmincon', 'Display', 'iter', 'Algorithm', 'sqp');
[x_opt, fval] = fmincon(objFun, x0, [], [], Aeq, beq, lb, ub, [], options);
% Display the optimized parameters and the function value at the optimum
fprintf('Optimal parameters: x1 = %.4f, x2 = %.4f, x3 = %.4f\n', x_opt(1), x_opt(2), x_opt(3));
fprintf('Minimum function value: %.4f\n', fval);
This revised approach should help you correctly use fmincon for your optimization problem. Remember to replace the modello and plotting sections with your specific functions and plotting commands as needed.
Hope this helps.
Regards,
Nipun
