# Solve using genetic algorithm

5 views (last 30 days)
Akhil on 31 Jan 2024
Answered: Alan Weiss on 1 Feb 2024
How to change the following code inorder to get the values of x,y and w using genetic algorithm
x=optimvar('x',1,26);
y=optimvar('y',1,26);
w=optimvar('w',1,26);
f = 0;
for i = 1:numel(a)
r1 = reg1(i);
r2 = reg2(i);
f = f + w(r2) * sqrt((x(r1)-a(i))^2 + (y(r1)-b(i))^2) - w(r1) * sqrt((x(r2)-a(i))^2 + (y(r2)-b(i))^2);
end
x0=0;
y0=0;
w0=10;
%function f=ht(x,y,w)
% x=zeros(1,26);
% y=zeros(1,26);
%w=zeros(1,26);
%end
syms x y w [1 26]
%size(x);
%size(y);
%size(w);
expr_func = matlabFunction(f, 'Vars', {f,x, y,w,a,b,r1,r2});

Alan Weiss on 1 Feb 2024
I really don't understand what you are trying to do. You seem to be mixing up symbolic and numeric variables. If you want to use the genetic algorithm, then don't use symbolic variables (do not call syms or matlabFunction).
I don't know what your reg1 and reg2 functions or arrays are, so I cannot help you debug your code any further. And I do not see an objective function to minimize, unless it is your f expression.
If you want to use the problem-based approach, you need to create an optimization problem and initial points as shown in the documentation. I suggest that you read Problem-Based Optimization Workflow. Then call solve, which will probably call fmincon. If you want to use ga, then call solve with the syntax
sol = solve(prob,x0,Solver="ga")
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation