Vectorizing the fitness and constraints for the genetic algorithm
2 views (last 30 days)
Show older comments
Hi everyone,
I have an optimization problem with an binary variable, which I'm solving with the genetic algorithm from the Global Optimization Toolbox. I wrote my fitness and constraints with nested for loops. I constrainted the variables to integer and set the lower and upper bounds to 0 and 1. Everything works fine.
Now I wanted to vectorize my code, to improve the speed of the ga. Thats how the my fitness now looks like:
function z = myFitness_vec(y, W, K, M, cst)
cst = reshape(permute(cst,[2 1 3]), 1, numel(cst));
z = bsxfun(@times, cst, y );
z = sum(z);
end
And the constraints:
function [ineq, eq] = myConstraints_vec(y, W, K, M, a, c, t, tc)
yMat = permute(reshape(y, K, M, W), [2 1 3]);
eq1 = sum(yMat(2:11,:,:), 2) - 1;
eq1 = reshape(eq1, 1, numel(eq1));
ineq1_vec = sum(yMat(12:21,:,:), 2) - 1;
ineq1_vec = reshape(ineq1, 1, numel(ineq1));
a = a(:);
c = reshape(c, 1, []);
ineq2 = sum(sum(bsxfun(@times, a, yMat), 1), 3) - c;
ineq2 = reshape(ineq2, 1, numel(ineq2));
t = t(:);
tc = reshape(tc, 1, []);
ineq3 = sum(sum(bsxfun(@times, t, yMat), 1), 3) - tc;
ineq3 = reshape(ineq3, 1, numel(ineq3));
eq = [];
ineq = [-eq_1, eq_1, -ineq_1, ineq_2, ineq_3];
end
[With a(1:M), c(1:K), t(1:M), tc(1:K), d(1:K,1:K), i(1:M,1:M), cst(1:M,1:K,1:W) and y(1:M*K*W).]
But now, when I try to use the ga with these functions and the 'UseVectorized' option on 'true' I get an error. If I use the ga without the 'UseVectorized' option it works like with the functions written with loops.
So maybe I just didn't unterstand Vectorization correctly?
1 Comment
Answers (0)
See Also
Categories
Find more on Genetic Algorithm in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!