单设施选址-重心法-Matlab
题目 :
有A,B,C,D四个零售点,现给出需求 W j W_{\rm{j}} Wj/(吨), a j a_{\rm{j}} aj/(每公里运费),且已知各点坐标,现要求根据四个零售店去确定一个仓库的位置。
零售点 | W j W_{\rm{j}} Wj | a j a_{\rm{j}} aj | ( x i , y i ) ({x_i},{y_i}) (xi,yi) |
---|---|---|---|
A | 2 | 5 | (2,2) |
B | 3 | 5 | (11,3) |
C | 2.5 | 5 | (10,8) |
D | 1 | 5 | (4,9) |
现根据重心法定义编写matlab代码求解如下:
主函数
clc;clear all;
zuobiao=[2,2;11,3;10,8;4,9];
w=[2,3,2.5,1];
a=[5,5,5,5];
num=1;
%计算初始坐标及运费
[x0,y0,A0,dis]=new_zuobiao(zuobiao,w,a);
disp(['初始重心坐标为:(',num2str(x0),',',num2str(y0),')']);
q_yunfei=A0; %上一次计算的运费
h_yunfei=0; %迭代后计算的运费
while 1%计算迭代后的坐标及运费
[xi,yi,A,dis_i]=diedai_zuobiao(zuobiao,w,a,dis,num);
disp(['第',num2str(num),'次迭代重心坐标为:(',num2str(xi),',',num2str(yi),')']);
h_yunfei=A;
num=num+1;
dis=dis_i;
%判断是否满足运费条件
if (h_yunfei>q_yunfei)break;
end
q_yunfei=h_yunfei;
end
function [x0,y0,A0,dis]=new_zuobiao(zuobiao,w,a)
%初始化参数
n=size(zuobiao,1);
he1=zeros(n,1);
he2=zeros(n,1);
he3=zeros(n,1);
dis=zeros(n,1);
A=zeros(n,1);
%计算重心坐标
for i=1:nhe1(i)=a(i)*w(i)*zuobiao(i,1);he2(i)=a(i)*w(i);he3(i)=a(i)*w(i)*zuobiao(i,2);
end
x0=sum(he1)/sum(he2);
y0=sum(he3)/sum(he2);
%计算运距以及运费
for i=1:n
dis(i)=sqrt((x0-zuobiao(i,1))^2+(y0-zuobiao(i,2))^2);
A(i)=a(i)*w(i)*dis(i);
disp(['第',num2str(i),'个地点的初始运距:',num2str(dis(i))]);
end
A0=sum(A);
disp(['初始运费:',num2str(A0)]);
end
function [xi,yi,A,dis_i]=diedai_zuobiao(zuobiao,w,a,dis,num)
%初始化参数
n=size(zuobiao,1);
he1=zeros(n,1);
he2=zeros(n,1);
he3=zeros(n,1);
dis_i=zeros(n,1);
Ai=zeros(n,1);
%计算迭代后的坐标
for i=1:nhe1(i)=a(i)*w(i)*zuobiao(i,1)/dis(i);he2(i)=a(i)*w(i)/dis(i);he3(i)=a(i)*w(i)*zuobiao(i,2)/dis(i);
end
xi=sum(he1)/sum(he2);
yi=sum(he3)/sum(he2);
%计算运距以及运费
for j=1:n
dis_i(j)=sqrt((xi-zuobiao(j,1))^2+(yi-zuobiao(j,2))^2);
Ai(j)=a(j)*w(j)*dis_i(j);
disp(['第',num2str(j),'个地点第',num2str(num),'次迭代运距:',num2str(dis_i(j))]);
end
A=sum(Ai);
disp(['第',num2str(num),'次迭代运费:',num2str(A)]);
end
运算迭代43次后结果如下: