MATLAB Answers

Minimise the sum of squared errors, with non linear constraints

16 views (last 30 days)
Lewis Marshall
Lewis Marshall on 26 Mar 2021
Edited: Matt J on 5 Apr 2021
hello i am trying to find the coefficient vlaues that minimises the sum of the squared erorrs between the eqaution ->
sigma_therory=((-(x(1) + x(2)./lamda(i)).*(2./lamda(i) - 2*lamda(i).^2))
and experimental data "sigma_c"
x(1) and x(2) are coefficient values in which im trying to calculate and "lamda" is the input variable to the experiment. x(1) >0 and x(1)+x(2)>0
I have generated this code which i think does what i require, however i know what i have wirtten in the for loop is poor code and ineffifcient as it takes very long to run, any help on how to improve this would be greatly appreicated.
y=0
for i=1:length(lamda)
fun{i}=@(x) y+((-(x(1) + x(2)./lamda(i)).*(2./lamda(i) - 2*lamda(i).^2))-sigma_c(i))^2;
y=fun; %save the output of the function to be added to the next itteration
end
x0=[1 -1];
A=[-1,0];
b=[0];
[xf,fval]=fmincon(fun,x0,A,b,[],[],[],[],@nolin);
function [c,ceq]=nolin(x) %to implement the coefficient x(1)+x(2)>0
c(1)=-x(1)-x(2)
ceq=[]
end

Answers (2)


Matt J
Matt J on 4 Apr 2021
Edited: Matt J on 5 Apr 2021
The unnecessary use of nonlinear constraints can slow things down. Your constraints are in fact linear, and should be expressed like this,
x0=[1 -1];
A=[-1,-1];
b=[0];
lb=[0,-inf];
[xf,fval]=fmincon(fun,x0,A,b,[],[],lb,[]);
Also, the way you have expressed your objective function should be giving you errors. You almost surely want this, instead of what you have above:
lamda=lamda(:); sigma_c=sigma_c(:);
fun=@(x) norm( (-(x(1) + x(2)./lamda).*(2./lamda - 2*lamda.^2))-sigma_c).^2 ;

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!