% 定义效益表
water_supply = [0, 100, 200, 300, 400, 500];
benefits_a = [0, 30, 70, 90, 120, 130];
benefits_b = [0, 50, 100, 110, 110, 110];
benefits_c = [0, 40, 60, 110, 120, 120];
% 插值方法使得任意供水量求效益成为可能
benefit_a_interp = @(x) interp1(water_supply, benefits_a, x, 'linear', 'extrap');
benefit_b_interp = @(x) interp1(water_supply, benefits_b, x, 'linear', 'extrap');
benefit_c_interp = @(x) interp1(water_supply, benefits_c, x, 'linear', 'extrap');
% 适应度函数
function total_benefit = fitness(x)
benefit_a = benefit_a_interp(x(1));
benefit_b = benefit_b_interp(x(2));
benefit_c = benefit_c_interp(x(3));
total_benefit = -(benefit_a + benefit_b + benefit_c); % 遗传算法默认是最小化问题,所以取负值
end
% 定义变量的上下界
lb = [0, 0, 0]; % lower bounds
ub = [500, 500, 500]; % upper bounds
% 定义总约束(供水总量不能超过500万立方米)
function [c, ceq] = water_constraint(x)
c = sum(x) - 500; % 不等式约束
ceq = []; % 无等式约束
end
% 使用遗传算法进行优化
opts = optimoptions(@ga, 'Display', 'iter'); % 显示迭代过程
nvars = 3; % 变量数目
objective = @fitness;
[x_opt, fval_opt] = ga(objective, nvars, [], [], [], [], lb, ub, @water_constraint, opts);
% 输出结果
disp('Optimal Water Supply Scheme:')
fprintf('Supply to A: %.2f million cubic meters\n', x_opt(1));
fprintf('Supply to B: %.2f million cubic meters\n', x_opt(2));
fprintf('Supply to C: %.2f million cubic meters\n', x_opt(3));
fprintf('Maximum Total Benefit: %.2f million yuan\n', -fval_opt); % 记得这里要取负值恢复原值
% 将适应度函数放在文件末尾
function total_benefit = fitness(x)
benefit_a_interp = @(x) interp1([0, 100, 200, 300, 400, 500], [0, 30, 70, 90, 120, 130], x, 'linear', 'extrap');
benefit_b_interp = @(x) interp1([0, 100, 200, 300, 400, 500], [0, 50, 100, 110, 110, 110], x, 'linear', 'extrap');
benefit_c_interp = @(x) interp1([0, 100, 200, 300, 400, 500], [0, 40, 60, 110, 120, 120], x, 'linear', 'extrap');
benefit_a = benefit_a_interp(x(1));
benefit_b = benefit_b_interp(x(2));
benefit_c = benefit_c_interp(x(3));
total_benefit = -(benefit_a + benefit_b + benefit_c); % 遗传算法默认是最小化问题,所以取负值
end
% 总约束函数(供水总量不能超过500万立方米)
function [c, ceq] = water_constraint(x)
c = sum(x) - 500; % 不等式约束
ceq = []; % 无等式约束
end