资源简介
LEACH协议在matlab上的仿真代码,并配有简单的性能输出
代码片段和文件信息
function LEACH_o = LEACH_o()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 初始化参数%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all;
clear;%清除变量
xm=200;%设置区域为200*200
ym=200;
sink.x=100;%sink(汇聚)节点坐标
sink.y=350;
n=500;%区域内的节点数目
p=0.02;% 节点成为簇头的概率
Eo=1;%节点初始能量
ETX=50*0.000000001;%发射单位报文损耗能量
ERX=50*0.000000001;%接收单位报文损耗能量
Efs=10*0.000000000001;%自由空间能量
Emp=0.0013*0.000000000001;%衰减空间能量
EDA=5*0.000000001;%多路径衰减能量
rmax=2500;%最大的轮数
do=sqrt(Efs/Emp); %计算do 通信半径
flag_first_dead=0;%第一个节点死亡的标志变量
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%随机生成n个节点、定义sink节点%%%%%%%%%%%%%%%%%%%%%%%%%
figure(1);%输出图形
for i=1:1:n %遍历节点
S(i).xd=rand(11)*xm;%1行1列矩阵
XR(i)=S(i).xd;%随机生成的X轴
S(i).yd=rand(11)*ym;
YR(i)=S(i).yd;%随机生成的Y轴
S(i).G=0;%
S(i).type=‘N‘;%节点类型为普通
plot(S(i).xdS(i).yd‘b:o‘);%输出节点,用o表示
hold on;
end
S(n+1).xd=sink.x;%汇聚节点X轴坐标
S(n+1).yd=sink.y;%汇聚节点Y轴坐标
%plot(S(n+1).xdS(n+1).yd‘x‘); %输出汇聚节点,用x表示
hold off;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%开始每轮竞选和传输%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
aa=0.05;
bb=0.07;
cc=0.1;
for EE=[aabb]
for i=1:1:n %遍历节点
S(i).Eo=Eo;%记录初始能量为E0
S(i).Ec=S(i).Eo;%设置初始能量
S(i).type=‘N‘;
end
for r=0:1:rmax%遍历每一轮
dead=0;%节点死亡数
packets_TO_BS=0;%传输sink节点报文数
packets_TO_CH=0;%传输簇头的报文数
PACKETS_TO_CH(r+1)=0;%每轮传送到簇头的报文数
PACKETS_TO_BS(r+1)=0;%每轮传送到基站的报文数
for i=1:1:n%遍历节点
S(i).type=‘N‘;
%Ea(r+1i)=S(i).Ec;
if(mod(r round(1/p))==0)%如果一轮循环结束
S(i).G=0;%重置所有节点成为备选簇头
%S(i).Eo=S(i).Ec;%更新节点初始能量值
end
if (S(i).Ec<=0)%检查是否有节点死亡
dead=dead+1;%节点死亡数+1
end
end
STATISTICS(r+1).DEAD=dead;%记录r轮累计死亡节点数
DEAD(r+1)=dead;%记录r轮后死亡节点数
if (dead==1)%记录第一个节点死亡
if(flag_first_dead==0)%第一个节点死亡周期
first_dead=r+1;%第一个节点死亡轮数
flag_first_dead=1;%第一个死亡节点标志
end
end
countCHs=0;%簇头计数量
cluster=0;%C(cluster)簇头数组中的编号量
for i=1:1:n%遍历所有节点
if(S(i).Ec>0)%节点剩余能量大于0
temp_rand=rand;%生成随机数
if ((S(i).G)<=0)%判断i是否为候选簇头
switch EE
case aa
Tn = p / (1 - p * mod(rround(1/p)));
%ETaa(r+1i)=S(i).Ec;
case bb
if (mod(r100)==0)
p=1.2*p;
Tn = p / (1 - p * mod(rround(1/p)));
p
end
%ETbb(r+1i)=S(i).Ec;
case cc
p=p*(1/r+1);
评论
共有 条评论