How can I store the value at each iteration of a genetic algorithm?

52 次查看(过去 30 天)
I have a simple function and two constraints for my genetic algorithm code
ObjFcn = @myFitness;
nvars = 2; %number of variables
LB = [0 0]; %lower bound
UB = [1 13]; %upper bound
ConsFcn = @myConstraints;
[x,fval] = ga(ObjFcn,nvars,[],[],[],[],LB,UB,ConsFcn,opts);
function y = myFitness(x)
y = 100*(x(1)^2-x(2))^2 + (1-x(1))^2;
end
function [c,c_eq] = myConstraints(x)
c = [x(1)*x(2) + x(1) - x(2) + 1.5; 10 - x(1)*x(2)];
c_eq = [];
end
I would like to store the values of x at each function evaluation, as well as keep track of the generation. I've found a similar question here but I don't really understand what the solution meant as it wasn't very clear. I believe I need to tell my fitness function to store values of the GA function so when the GA function reads the fitness function the input parameters at that iteration are saved... but I would like help on how the syntax would work for such a thing. Any help is appreciated!
I've also looked at the GA options and was unable to find help with my specific issue.

采纳的回答

Stephan
Stephan 2019-4-2
Hi,
you coultd try this way:
[x,fval,vals] = solve_problem
function [x,fval,vals] = solve_problem
ObjFcn = @myFitness;
nvars = 2; %number of variables
LB = [0 0]; %lower bound
UB = [1 13]; %upper bound
ConsFcn = @myConstraints;
iter = 1;
vals = [];
[x,fval] = ga(ObjFcn,nvars,[],[],[],[],LB,UB,ConsFcn);
function y = myFitness(x)
y = 100*(x(1)^2-x(2))^2 + (1-x(1))^2;
vals(iter,1:2) = x;
iter = iter+1;
end
function [c,c_eq] = myConstraints(x)
c = [x(1)*x(2) + x(1) - x(2) + 1.5; 10 - x(1)*x(2)];
c_eq = [];
end
end
After running this you can plot how x(1) and x(2) change over the iterations:
yyaxis left
plot(vals(:,1))
yyaxis right
plot(vals(:,2))
x-vals.PNG
Best regards
Stephan
  1 个评论
Sylvain Cornelus
Sylvain Cornelus 2019-4-2
Thank you Stephan! Exactly what I was looking for. I'll read up on the ga function to figure out how to store the generation.

请先登录,再进行评论。

更多回答(1 个)

UNAL
UNAL 2019-9-13
You can also extract the data directly from the graph that is obtained by configuring the options:
options = optimoptions('ga','PlotFcn', @gaplotbestf);
After obtaining the graph you can extract ist data:
fig = gcf;
dataObjs = findobj(fig,'-property','YData');
y1 = dataObjs(1).YData;
x1 = dataObjs(1).XData;
figure(7)
plot(x1,y1,'*r')
  1 个评论
djamel
djamel 2022-12-23
Many thanks for your feedback , i was seraching on this solutions for long time .
It was very useful for me .
Many thanks .

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Genetic Algorithm 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by