extend a optimization function in a loop
Show older comments
I want to create some point that distance beteen each two point must not be exceed from a specific value and at the same time these points must be close to each other as more as possible. I use spherical coordinate and wrote this code(for two point). as in each itration a "squre" term adds to the "fun", what's the best way to develope this code for any arbitrary number of point (for example 300 point) without repeating "elseif" loop . I atached my code and "nonlcon" functions
clc
clear
X(1) = 0;
Y(1) = 0;
Z(1) = 0;
for i=2:3
if i == 2
options = optimoptions('fmincon','MaxFunctionEvaluations',10000,'MaxIterations',5000);
multiopts = {'MaxIterations','Algorithm','MaxFunctionEvaluations'};
options2 = resetoptions(options,multiopts);
fun = @(x)sqrt( (x(1)*cos(x(2))*sin(x(3))-X(i-1))^2 + (x(1)*sin(x(2))*sin(x(3))-Y(i-1))^2 + (x(1)*cos(x(3))-Z(i-1))^2 );
lb = [2,0,0];
ub = [2,2*pi,2*pi];
x0 = [2,4.706221831,3.166020255];
A = [];
b = [];
Aeq = [];
beq = [];
nonlcon = @distance;
[x,fval] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);
X(i) = x(1)*cos(x(2))*sin(x(3));
Y(i) = x(1)*sin(x(2))*sin(x(3));
Z(i) = x(1)*cos(x(3));
ROH(i) = x(1);
THETA(i) = x(2);
PHI(i) = x(3);
elseif i==3
options = optimoptions('fmincon','MaxFunctionEvaluations',10000,'MaxIterations',5000);
multiopts = {'MaxIterations','Algorithm','MaxFunctionEvaluations'};
options2 = resetoptions(options,multiopts);
fun = @(x)( sqrt((x(1)*cos(x(2))*sin(x(3))-X(i-1))^2 + (x(1)*sin(x(2))*sin(x(3))-Y(i-1))^2 + (x(1)*cos(x(3))-Z(i-1))^2) + sqrt((x(1)*cos(x(2))*sin(x(3))-X(i-2))^2 + (x(1)*sin(x(2))*sin(x(3))-Y(i-2))^2 + (x(1)*cos(x(3))-Z(i-2))^2) );
lb = [2,0,0];
ub = [2,2*pi,2*pi];
x0 = [2,3.743600534,2.108470198];
A = [];
b = [];
Aeq = [];
beq = [];
t = i;
nonlcon = @(x)distance2(x, X, Y, Z, t);
[x,fval] = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options);
X(i) = x(1)*cos(x(2))*sin(x(3));
Y(i) = x(1)*sin(x(2))*sin(x(3));
Z(i) = x(1)*cos(x(3));
ROH(i) = x(1);
THETA(i) = x(2);
PHI(i) = x(3);
end
end
3 Comments
Walter Roberson
on 24 Oct 2021
Have you examined Problem Based Optmization ?
sajad mhmzd
on 24 Oct 2021
Answers (0)
Categories
Find more on Direct Search in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!