How can I integrate into a fitness function another code.
6 views (last 30 days)
Show older comments
am trying to use the GA on my existing project(simulator). So I have created the algorithm and I am trying to integrate it into my existing code. So what I am trying to do is instead of using the "y" function, I am trying to use my project code. But it seems that it does not like it when I am commenting out the Y, or even when I am using y=@Project_code;
clear all;
car_range_max=[98,52];
car_range_min=[-98,-52];
opts=gaoptimset('PlotFcns',@gaplotbestf,'PopulationSize',10,'PopInitRange',[car_range_max;car_range_min],'Generations',20,'CrossoverFraction',0.7,'TolFun',0.0001,'MutationFcn',@mutationadaptfeasible);
global z
z = [];
nvars = 2;
[bestx, minfval_M]=ga(@untitled2,nvars,[],[],[],[],car_range_max,car_range_min,[],opts);
bestx
fval
%/*********************** another file ***************************************/
function y= untitled2(x)
global z
max_speed=x(1);
acc_speed=x(2);
[y,car_energy,car_travel_time]= Project_code(max_speed,acc_speed); % Project_code is expecting the values from max_speed and acc_speed
z=[z;max_speed,acc_speed,car_energy,car_travel_time];
end
%Bellow is redundant as I will use the function Project_code and not the y
%funtion
%function [y, car_energy,car_travel_time] = Project_code(max_speed, acc_speed)
% y = max_speed+acc_speed+4*max_speed+4*acc_speed+8;
% max_speed = randi(10); acc_speed = randi(10);
%end
0 Comments
Answers (1)
Walter Roberson
on 21 Feb 2022
global z
z = [];
nvars = 2;
[bestx, fval] = ga(@untitled2, nvars)
z
function y = untitled2(x)
global z
max_speed=x(1);
acc_speed=x(2);
[y, a, b] = Project_code(max_speed, acc_speed);
z=[z;max_speed,acc_speed,a,b]; % store the data into a table
end
function [y, a, b] = Project_code(max_speed, acc_speed)
y = max_speed^2+acc_speed^2+4*max_speed+4*acc_speed+8;
a = randi(10); b = randi(10);
end
5 Comments
Walter Roberson
on 21 Feb 2022
Well that's a problem.
If Project_Code is currently a script that expects to receive values in certain variables and make assignments to particular variables... then it is really recommended that you convert it to a be a function. Calling a script from a function can lead to subtle problems.
See Also
Categories
Find more on Genetic Algorithm 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!