clc
clear all
close all
global distMatrix;
% 通讯半径设定
txRange = 0.05;
% 定义节点的数量
no_of_nodes=100;
% 给最后的节点定义个值
final_clock_val=ceil((no_of_nodes)^1.5);
% 给每个节点做标记
node_val=1:100%[5 4.6 6 5.5 6.2 3.8 7.1 3.4 6.3 7.2];
% actual average
actual_avr=mean(node_val);
% 定义随机节点x坐标位置
node_x=rand(1,no_of_nodes);
% 定义随机节点y坐标位置
node_y=rand(1,no_of_nodes);
% 数据可到达赋1
packet_acceptance=1;
% 从第一个节点到最后一个节点判断可达性
for j=1:final_clock_val
if packet_acceptance==1
% 随机给目的节点坐标赋值
xd=rand; yd=rand;
end
% 随机从节点中找一个源节点,源节点乘以0~1之间随机数
s=ceil(no_of_nodes*rand);
% 节点数据信息
ms=[node_val(s) node_x(s) node_y(s) xd yd];
% 节点到目的节点距离
distance=( (node_x-xd).^2 + (node_y-yd).^2 ).^(1/2);
% 找到距离目的节点最近的节点
[val,d]=min(distance);
% 创建一个no_of_nodes*no_of_nodes的零矩阵
distMatrix = zeros(no_of_nodes,no_of_nodes);
%循环计算节点之间的距离
for i=1:no_of_nodes
for j=1:no_of_nodes
distMatrix(i,j)=sqrt((node_x(i)-node_x(j))^2 + (node_y(i)-node_y(j))^2);
%distance between node pairs
end
end
% 如果小于通讯半径范围内,就表示可以将数据传给此节点,
%将可达节点表示出来
global connMatrix;
connMatrix = ( distMatrix < txRange);
%___________________________________________________________
% 下面是画节点函数
%
%draw_nodes(no_of_nodes,node_x,node_y,node_val,s,d,xd,yd);
%function draw_nodes(no_of_nodes,node_x,node_y,node_val,s,d,xd,yd)
clear message_chain
% 延迟0.5秒让人看得清楚循环的过程
delay=0.2;
%随机定义k,在通讯半径内随机取点作为下一跳位置
k=1;
%将源节点赋值可到达节点
message_chain(k)=s;
%将停止链接赋值一
stop_cond=1;
%判断节点是否可到达,不可到达则跳出循环
while(stop_cond)
oldistance=inf
for i=1:no_of_nodes
if isempty(find(message_chain==i, 1))
% 判断节点是否在通讯半径以内是否可达% 计算距离
newdistance=( (node_x(i)-node_x(message_chain(k)))^2 + (node_y(i)-node_y(message_chain(k)))^2 )^(1/2);
if newdistance<oldistance
new_node=i;
oldistance=newdistance;
end
end
end
if oldistance<inf
%邻居节点判断是否在通讯半径内并循环
k=k+1;
message_chain(k)=new_node;
if new_node==d
stop_cond=0;
end
else
stop_cond=0;
end
end
%随机产生no_of_nodes个节点
for f=1:no_of_nodes
plot(node_x(f),node_y(f),'.b','linewidth',2.5)
hold on
text(node_x(f),node_y(f),num2str(node_val(f)))
end
%画源节点
plot(xd,yd,'or','linewidth',3)
%画目的节点
plot(node_x(s),node_y(s),'ok','linewidth',3)
%将通讯半径内可到的节点随机选一个发送数据
for j=1:numel(message_chain)-1
%将数据依次传给可达节
plot(node_x(message_chain(j:j+1)),node_y(message_chain(j:j+1)))
%设置横纵坐标
axis([0 1 0 1])
drawnow;
%延迟0.2秒
pause(delay)
end
hold off
end
%___________________________________________________________
if rand >0.5
% 接受信息或拒绝接受
packet_acceptance=1;
node_val(s)=(node_val(s)+node_val(d))/2;
node_val(d)=node_val(s);
else
packet_acceptance=0;
% 可接受节点设置为零,信息到达目的节点
xd=node_x(d); yd=node_y(d);
end

猰貐的新时代
- 粉丝: 1w+
最新资源
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


