0% found this document useful (0 votes)
22 views

100 WN

This document appears to be an experiment report submitted by a student named Ishita Jain to their instructor Ms. Yashima Hooda. It includes 7 experiments conducted in MATLAB on wireless network routing protocols and clustering algorithms. The experiments cover topics like K-means clustering, LEACH routing, PEGASIS, DSDV, AODV, and flooding protocols. Each experiment section includes the aim, MATLAB code implemented, and output of the code.

Uploaded by

drishtianand732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

100 WN

This document appears to be an experiment report submitted by a student named Ishita Jain to their instructor Ms. Yashima Hooda. It includes 7 experiments conducted in MATLAB on wireless network routing protocols and clustering algorithms. The experiments cover topics like K-means clustering, LEACH routing, PEGASIS, DSDV, AODV, and flooding protocols. Each experiment section includes the aim, MATLAB code implemented, and output of the code.

Uploaded by

drishtianand732
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

INDIRA GANDHI DELHI TECHNICAL

UNIVERSITY FOR WOMEN

Wireless Networks
Practical File
BCS-302

Submitted by: Submitted to:


Name: Ishita Jain Ms. Yashima Hooda
Enrolment No: 10001012020 Junior Research Fellow
Batch: CSE-2, A2 CSE Department
B.Tech., 6th Semester IGDTUW
Index
S. No. Experiment Name Date Signature

1 Introduction to MATLAB with calculator program

2 Implementation of any one Clustering Technique on MATLAB

3 Implementation of K – Means Clustering on MATLAB

4 Implementation of LEACH Routing Protocol on MATLAB

5 Implementation of PEGASIS Protocol on MATLAB

6 Implementation of DSDV Routing Protocol on MATLAB

7 Implementation of AODV Routing Protocol on MATLAB

8 Implementation of any one Flooding Protocol on MATLAB


Experiment No. 1
Aim: Introduction to MATLAB with calculator program
Code:
close all;
clear;
clc;
a=input('ENTER THE FIRST NUMBER : ');
b=input('ENTER THE SECOND NUMBER : ');
choice=0;

while choice~=9
fprintf('\n\t menu \n\t======\n');
fprintf('\n 1.Sum');
fprintf('\n 2.Difference');
fprintf('\n 3.Multiplication');
fprintf('\n 4.Division');
fprintf('\n 5.Sine');
fprintf('\n 6.Cosine');
fprintf('\n 7.Logarithm');
fprintf('\n 8.Exponential');
fprintf('\n 9.Exit');
choice=input('\n Choice: ');

switch choice
case 1
sum=a+b;
fprintf('\n Sum of number :%d\n',sum);
case 2
difference=a-b;
fprintf('\n Sum of number :%d\n',difference);
case 3
multi=a*b;
fprintf('\n Sum of number :%d\n',multi);
case 4
division=a/b;
fprintf('\n Sum of number :%d\n',division);
case 5
sinea= sin(a);
sineb= sin(b);
fprintf('\n Sum of number :%d & %d\n',sinea,sineb);
case 6
cosa=cos(a);
cosb=cos(b);
fprintf('\n Sum of number :%d & %d\n',cosa,cosb);
case 7
log_a=log(a);
log_b=log(b);
fprintf('\n Sum of number :%d & %d\n',log_a,log_b);
case 8
exp_a=exp(a);
exp_b=exp(b);
fprintf('\n Sum of number :%d & %d\n',exp_a,exp_b);
case 9
fprintf('Exiting...\n');
otherwise
disp('ERROR');
end
end

Output:
Experiment No. 2
Aim: Implementation of any one Clustering Technique on MATLAB

Code:
close all;
clear;
clc;
load fisheriris
X = meas;
y = categorical(species);
eva = evalclusters(X,'kmeans','CalinskiHarabasz','KList',1:10)
plot(eva)
categories(y)
Xred = nnmf(X,2);
gscatter(Xred(:,1),Xred(:,2),y)
xlabel('Column 1')
ylabel('Column 2')
grid on

Output:
Experiment No. 3
Aim: Implementation of K – Means Clustering on MATLAB
Code:
close all;
clear;
clc;
rng default; % For reproducibility
X = [randn(100,2)*0.75+ones(100,2);
randn(100,2)*0.5-ones(100,2)];
opts = statset('Display','final');
[idx,C]=kmeans(X,4,'Distance','cityblock','Replicates',5, 'Options',opts);
plot(X(idx==1,1),X(idx==1,2),'r.','MarkerSize',12);
hold on;
plot(X(idx==2,1),X(idx==2,2),'b.','MarkerSize',12);
plot(X(idx==3,1),X(idx==3,2),'g.','MarkerSize',12);
plot(X(idx==4,1),X(idx==4,2),'y.','MarkerSize',12);
plot(C(:,1),C(:,2),'Kx','MarkerSize',15,'LineWidth',3);
legend('Cluster 1','Cluster 2', 'Cluster 3', 'Cluster 4', 'Centroids', 'Location', 'NW');
title('Cluster Assignments and centroids');
hold off;
for i=1:size(C, 1)
display(['Centroid ', num2str(i), ': X1 = ', num2str(C(i, 1)), '; X2 = ', num2str(C(i, 2))]);
end

Output:
Experiment No. 4
Aim: Implementation of LEACH Routing Protocol on MATLAB
Code:
close all;
clear;
clc;
%%%%%%%%%%%%%%%%%%%% Network Establishment Parameters
%%%%%%%%%%%%%%%%%%%%
%%% Area of Operation %%%
% Field Dimensions in meters %
xm=100;
ym=100;
x=0; % added for better display results of the plot
y=0; % added for better display results of the plot
% Number of Nodes in the field %
n=100;
% Number of Dead Nodes in the beggining %
dead_nodes=0;
% Coordinates of the Sink (location is predetermined in this simulation) %
sinkx=50;
sinky=200;
%%% Energy Values %%%
% Initial Energy of a Node (in Joules) %
Eo=2; % units in Joules
% Energy required to run circuity (both for transmitter and receiver) %
Eelec=50*10^(-9); % units in Joules/bit
ETx=50*10^(-9); % units in Joules/bit
ERx=50*10^(-9); % units in Joules/bit
% Transmit Amplifier Types %
Eamp=100*10^(-12); % units in Joules/bit/m^2 (amount of energy spent by the amplifier to
transmit the bits)
% Data Aggregation Energy %
EDA=5*10^(-9); % units in Joules/bit
% Size of data package %
k=4000; % units in bits
% Suggested percentage of cluster head %
p=0.05; % a 5 percent of the total amount of nodes used in the network is proposed to give good
results
% Number of Clusters %
No=p*n;
% Round of Operation %
rnd=0;
% Current Number of operating Nodes %
operating_nodes=n;
transmissions=0;
temp_val=0;
flag1stdead=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%% End of Parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Creation of the Wireless Sensor Network %%%


% Plotting the WSN %
for i=1:n
SN(i).id=i; % sensor's ID number
SN(i).x=rand(1,1)*xm; % X-axis coordinates of sensor node
SN(i).y=rand(1,1)*ym; % Y-axis coordinates of sensor node
SN(i).E=Eo; % nodes energy levels (initially set to be equal to "Eo"
SN(i).role=0; % node acts as normal if the value is '0', if elected as a cluster head it gets the value
'1' (initially all nodes are normal)
SN(i).cluster=0; % the cluster which a node belongs to
SN(i).cond=1; % States the current condition of the node. when the node is Operational its value
is =1 and when dead =0
SN(i).rop=0; % number of rounds node was operational
SN(i).rleft=0; % rounds left for node to become available for Cluster Head election
SN(i).dtch=0; % nodes distance from the cluster head of the cluster in which he belongs
SN(i).dts=0; % nodes distance from the sink
SN(i).tel=0; % states how many times the node was elected as a Cluster Head
SN(i).rn=0; % round node got elected as cluster head
SN(i).chid=0; % node ID of the cluster head which the "i" normal node belongs to

hold on;
figure(1)
plot(x,y,xm,ym,SN(i).x,SN(i).y,'ob',sinkx,sinky,'*r');
title 'Wireless Sensor Network';
xlabel '(m)';
ylabel '(m)';
end
%%%%%% Set-Up Phase %%%%%%

while operating_nodes>0
% Displays Current Round %
rnd
% Threshold Value %
t=(p/(1-p*(mod(rnd,1/p))));
% Re-election Value %
tleft=mod(rnd,1/p);
% Reseting Previous Amount Of Cluster Heads In the Network %
CLheads=0;
% Reseting Previous Amount Of Energy Consumed In the Network on the Previous RounD %
energy=0;

% Cluster Heads Election %


for i=1:n
SN(i).cluster=0; % reseting cluster in which the node belongs to
SN(i).role=0; % reseting node role
SN(i).chid=0; % reseting cluster head id
if SN(i).rleft>0
SN(i).rleft=SN(i).rleft-1;
end
if (SN(i).E>0) && (SN(i).rleft==0)
generate=rand;
if generate< t
SN(i).role=1; % assigns the node role of acluster head
SN(i).rn=rnd; % Assigns the round that the cluster head was elected to the data table
SN(i).tel=SN(i).tel + 1;
SN(i).rleft=1/p-tleft; % rounds for which the node will be unable to become a CH
SN(i).dts=sqrt((sinkx-SN(i).x)^2 + (sinky-SN(i).y)^2); % calculates the distance between
the sink and the cluster hea
CLheads=CLheads+1; % sum of cluster heads that have been elected
SN(i).cluster=CLheads; % cluster of which the node got elected to be cluster head
CL(CLheads).x=SN(i).x; % X-axis coordinates of elected cluster head
CL(CLheads).y=SN(i).y; % Y-axis coordinates of elected cluster head
CL(CLheads).id=i; % Assigns the node ID of the newly elected cluster head to an array
end
end
end
% Fixing the size of "CL" array %
CL=CL(1:CLheads);

% Grouping the Nodes into Clusters & caclulating the distance between node and cluster head %
for i=1:n
if (SN(i).role==0) && (SN(i).E>0) && (CLheads>0) % if node is normal
for m=1:CLheads
d(m)=sqrt((CL(m).x-SN(i).x)^2 + (CL(m).y-SN(i).y)^2);
% we calculate the distance 'd' between the sensor node that is
% transmitting and the cluster head that is receiving with the following equation+
% d=sqrt((x2-x1)^2 + (y2-y1)^2) where x2 and y2 the coordinates of
% the cluster head and x1 and y1 the coordinates of the transmitting node
end
d=d(1:CLheads); % fixing the size of "d" array
[M,I]=min(d(:)); % finds the minimum distance of node to CH
[Row, Col] = ind2sub(size(d),I); % displays the Cluster Number in which this node belongs
too
SN(i).cluster=Col; % assigns node to the cluster
SN(i).dtch= d(Col); % assigns the distance of node to CH
SN(i).chid=CL(Col).id;
end
end

%%%%%% Steady-State Phase %%%%%%

% Energy Dissipation for normal nodes %


for i=1:n
if (SN(i).cond==1) && (SN(i).role==0) && (CLheads>0)
if SN(i).E>0
ETx= Eelec*k + Eamp * k * SN(i).dtch^2;
SN(i).E=SN(i).E - ETx;
energy=energy+ETx;
% Dissipation for cluster head during reception
if SN(SN(i).chid).E>0 && SN(SN(i).chid).cond==1 && SN(SN(i).chid).role==1
ERx=(Eelec+EDA)*k;
energy=energy+ERx;
SN(SN(i).chid).E=SN(SN(i).chid).E - ERx;
if SN(SN(i).chid).E<=0 % if cluster heads energy depletes with reception
SN(SN(i).chid).cond=0;
SN(SN(i).chid).rop=rnd;
dead_nodes=dead_nodes +1;
operating_nodes= operating_nodes - 1
end
end
end

if SN(i).E<=0 % if nodes energy depletes with transmission


dead_nodes=dead_nodes +1;
operating_nodes= operating_nodes - 1
SN(i).cond=0;
SN(i).chid=0;
SN(i).rop=rnd;
end
end
end

% Energy Dissipation for cluster head nodes %


for i=1:n
if (SN(i).cond==1) && (SN(i).role==1)
if SN(i).E>0
ETx= (Eelec+EDA)*k + Eamp * k * SN(i).dts^2;
SN(i).E=SN(i).E - ETx;
energy=energy+ETx;
end
if SN(i).E<=0 % if cluster heads energy depletes with transmission
dead_nodes=dead_nodes +1;
operating_nodes= operating_nodes - 1
SN(i).cond=0;
SN(i).rop=rnd;
end
end
end

if operating_nodes<n && temp_val==0


temp_val=1;
flag1stdead=rnd
end
% Display Number of Cluster Heads of this round %
%CLheads;

transmissions=transmissions+1;
if CLheads==0
transmissions=transmissions-1;
end

% Next Round %
rnd= rnd +1;

tr(transmissions)=operating_nodes;
op(rnd)=operating_nodes;

if energy>0
nrg(transmissions)=energy;
end

end

sum=0;
for i=1:flag1stdead
sum=nrg(i) + sum;
end
temp1=sum/flag1stdead;
temp2=temp1/n;
for i=1:flag1stdead
avg_node(i)=temp2;
end
% Plotting Simulation Results "Operating Nodes per Round" %
figure(2)
plot(1:rnd,op(1:rnd),'-r','Linewidth',2);
title ({'LEACH'; 'Operating Nodes per Round';})
xlabel 'Rounds';
ylabel 'Operational Nodes';
hold on;
% Plotting Simulation Results %
figure(3)
plot(1:transmissions,tr(1:transmissions),'-r','Linewidth',2);
title ({'LEACH'; 'Operational Nodes per Transmission';})
xlabel 'Transmissions';
ylabel 'Operational Nodes';
hold on;
% Plotting Simulation Results %
figure(4)
plot(1:flag1stdead,nrg(1:flag1stdead),'-r','Linewidth',2);
title ({'LEACH'; 'Energy consumed per Transmission';})
xlabel 'Transmission';
ylabel 'Energy ( J )';
hold on;
% Plotting Simulation Results %
figure(5)
plot(1:flag1stdead,avg_node(1:flag1stdead),'-r','Linewidth',2);
title ({'LEACH'; 'Average Energy consumed by a Node per Transmission';})
xlabel 'Transmissions';
ylabel 'Energy ( J )';
hold on;

Output:
Experiment No. 5
Aim: Implementation of PEGASIS Routing Protocol on MATLAB
Code:
close all;
clear;
clc;
%%%%%%%%%%%%%%%%%%%% Network Establishment Parameters
%%%%%%%%%%%%%%%%%%%%
%%% Area of Operation %%%
% Field Dimensions in meters %
xm=100;
ym=100;
x=0; % added for better display results of the plot
y=0; % added for better display results of the plot
% Number of Nodes in the field %
n=100;
% Number of Dead Nodes in the beggining %
dead_nodes=0;
% Coordinates of the Sink (location is predetermined in this simulation) %
sinkx=50;
sinky=200;
%%% Energy Values %%%
% Initial Energy of a Node (in Joules) %
Eo=2; % units in Joules
% Energy required to run circuity (both for transmitter and receiver) %
Eelec=50*10^(-9); % units in Joules/bit
ETx=50*10^(-9); % units in Joules/bit
ERx=50*10^(-9); % units in Joules/bit
% Transmit Amplifier Types %
Eamp=100*10^(-12); % units in Joules/bit/m^2 (amount of energy spent by the amplifier to
transmit the bits)
% Data Aggregation Energy %
EDA=5*10^(-9); % units in Joules/bit
% Size of data package %
k=4000; % units in bits
% Round of Operation %
rnd=0;
% Current Number of operating Nodes %
operating_nodes=n;
transmissions=0;
d(n,n)=0;
temp_dead=0;
dead_nodes=0;
selected=0;
flag1stdead=0;
count=0;
turn=0;
temp_val=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%% End of Parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% Creation of the Wireless Sensor Network %%%

% Plotting the WSN %


for i=1:n
SN(i).id=i; % sensor's ID number
SN(i).x=rand(1,1)*xm; % X-axis coordinates of sensor node
SN(i).y=rand(1,1)*ym; % Y-axis coordinates of sensor node
SN(i).E=Eo; % nodes energy levels (initially set to be equal to "Eo"
SN(i).cond=1; % States the current condition of the node. when the node is operational its value
is =1 and when dead =0
SN(i).dts=0; % nodes distance from the sink
SN(i).role=0; % node acts as normal if the value is '0', if elected as a cluster head it gets the value
'1' (initially all nodes are normal)
SN(i).pos=0;
SN(i).closest=0;
SN(i).prev=0;
SN(i).dis=0; % distance between two nodes headin towards to the cluster head from position 1
SN(i).dis2=0; % distance between two nodes headin towards to the cluster head from position 2
SN(i).order=0;
SN(i).sel=0; % states if the node has already operated for this round or not (if 0 then no, if 1 then
yes)
SN(i).rop=0; % number of rounds node was operational
SN(i).tel=0; % states how many times the node was elected as a Cluster Head
order(i)=0;
hold on;
figure(1)
plot(x,y,xm,ym,SN(i).x,SN(i).y,'ob',sinkx,sinky,'*r');
title 'Wireless Sensor Network';
xlabel '(m)';
ylabel '(m)';
end
% Calculates Distance Between Each Node and the Sink (Base Station) %
for i=1:n
SN(i).dts=sqrt((sinkx-SN(i).x)^2 + (sinky-SN(i).y)^2);
SN(i).Esink=Eelec*k + Eamp*k*(SN(i).dts)^2;
T(i)=SN(i).dts;
end

A=sort(T,'descend'); % Creates array A containing the distance between each node and the sink,
% sorted in an asceding order

A_id(1:n)=0;
% Creates array A_id which is sorted in a way that it's elements are
% aligned with those of A. Contains the node ID
for i=1:n
for j=1:n
if A(i)==SN(j).dts
A_id(i)=SN(j).id;
end
end
end

% Creation of d Array with shortest distances %

for i=1:n
SN(i).closest=0;
for j=1:n
d(j,i)=sqrt((SN(i).x-SN(j).x)^2 + (SN(i).y-SN(j).y)^2);
if d(j,i)==0
d(j,i)=9999;
end
end
end

for i=1:n
[M,I]=min(d(:,i)); % finds the minimum distance of node to CH
[Row, Col] = ind2sub(size(d),I); % displays the Cluster Number in which this node belongs too
SN(i).closest=Row; % assigns node to the cluster
SN(i).dis= d(Row,i); % assigns the distance of node to CH
end
% Choosing furthest node from sink %
for i=1:n
if SN(A_id(i)).E>0 && SN(A_id(i)).sel==0 && SN(A_id(i)).cond==1
set= A_id(i);
SN(set).sel=1;
SN(set).pos=1;
break;
end
end
order(1)=set;
temp=1;
while selected<n
min_dis=9999;
for i=1:n
if SN(i).sel==0
d=sqrt((SN(i).x-SN(set).x)^2 + (SN(i).y-SN(set).y)^2);
if d<min_dis
min_dis=d;
next=i;
end
end
end
selected=selected+1;
SN(set).closest=next;
SN(set).dis=min_dis;
SN(next).sel=1;
SN(next).prev=set;
SN(next).dis2=sqrt((SN(set).x-SN(next).x)^2 + (SN(set).y-SN(next).y)^2);
plot([SN(set).x SN(next).x], [SN(set).y SN(next).y])
hold on;
set=next;
temp=temp+1;
order(temp)=set;
end
order(n+1)=[];
SN(set).pos=2;
SN(set).dis=0;
SN(set).closest=0;
for i=1:n
if SN(i).closest==set && SN(i).pos==0;
SN(set).prev=i;
SN(set).dis2=sqrt((SN(i).x-SN(set).x)^2 + (SN(i).y-SN(set).y)^2);
end
end
while operating_nodes>0
energy=0;
for i=1:n
SN(i).role=0;
end
% Cluster Head Election %
cluster_head=mod(turn,n) +1;
if SN(cluster_head).cond==0
while SN(cluster_head).cond==0
turn=turn+1;
cluster_head=mod(turn,n) +1;
end
end
if SN(cluster_head).cond==1
SN(cluster_head).role=1;
SN(cluster_head).tel=SN(cluster_head).tel+1;
figure(1)
plot(SN(cluster_head).x,SN(cluster_head).y,'+r')
end
for i=1:n
if order(i)==cluster_head
cl_pos=i;
break;
end
end
for i=1:n
if SN(order(i)).E>0 && SN(order(i)).cond==1
if i<cl_pos
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==1 && SN(order(i)).role==0
ETx= Eelec*k + Eamp*k*SN(order(i)).dis^2;
SN(order(i)).E=SN(order(i)).E-ETx;
energy=energy+ETx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==0 && SN(order(i)).role==0
ERx=(EDA+Eelec)*k;
ETx= (EDA+Eelec)*k + Eamp*k*SN(order(i)).dis^2;
SN(order(i)).E=SN(order(i)).E-ETx-ERx;
energy=energy+ETx+ERx;
end
end
if i>cl_pos
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==2 && SN(order(i)).role==0
ETx= Eelec*k + Eamp*k*SN(order(i)).dis2^2;
SN(order(i)).E=SN(order(i)).E-ETx;
energy=energy+ETx;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==0 && SN(order(i)).role==0
ERx=(EDA+Eelec)*k;
ETx= (EDA+Eelec)*k + Eamp*k*SN(order(i)).dis2^2;
SN(order(i)).E=SN(order(i)).E-ETx-ERx;
energy=energy+ETx+ERx;
end
end
if i==cl_pos

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==0 && SN(order(i)).role==1
ERx=(EDA+Eelec)*k*2;
ETx= (EDA+Eelec)*k + Eamp*k*SN(order(i)).dts^2;
SN(order(i)).E=SN(order(i)).E-ETx-ERx;
energy=energy+ETx+ERx;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==1 && SN(order(i)).role==1
ERx=(EDA+Eelec)*k;
ETx= (EDA+Eelec)*k + Eamp*k*SN(order(i)).dts^2;
SN(order(i)).E=SN(order(i)).E-ETx-ERx;
energy=energy+ETx+ERx;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==2 && SN(order(i)).role==1
ERx=(EDA+Eelec)*k;
ETx= (EDA+Eelec)*k + Eamp*k*SN(order(i)).dts^2;
SN(order(i)).E=SN(order(i)).E-ETx-ERx;
energy=energy+ETx+ERx;
end
end
end
if SN(order(i)).E<=0 && SN(order(i)).cond==1
SN(order(i)).cond=0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==1 && SN(order(i)).role==0
if operating_nodes==1
done='OK'
else
t=i;
while SN(order(t)).cond==0 && t<n
t=t+1;
end
SN(order(t)).pos=1;
SN(order(t)).prev=0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==2 && SN(order(i)).role==0
if operating_nodes==1
done='OK';
else
t=i;
while SN(order(t)).cond==0 && t>1
t=t-1;
end
SN(order(t)).pos=2;
SN(order(t)).closest=0;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==0 && SN(order(i)).role==1
SN(order(i)).role=0;
after=i;
for l=after:n
if SN(order(l)).cond==1
break;
end
end
bef=i;
for j=bef:-1:1
if SN(order(j)).cond==1
break;
end
end
SN(order(j)).closest=order(l);
SN(order(l)).prev=order(j);
SN(order(j)).dis=sqrt((SN(order(l)).x-SN(order(j)).x)^2 + (SN(order(l)).y-
SN(order(j)).y)^2);
SN(order(l)).dis2=SN(order(j)).closest;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==1 && SN(order(i)).role==1
SN(order(i)).role=0;
t=i;
while SN(order(t)).cond==0 && t<n
t=t+1;
end
SN(order(t)).pos=1;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==2 && SN(order(i)).role==1
SN(order(i)).role=0;
t=i;
while SN(order(t)).cond==0 && t>1
t=t-1;
end
SN(order(t)).pos=2;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if SN(order(i)).pos==0 && SN(order(i)).role==0
after=i;
for l=after:n
if SN(order(l)).cond==1
break;
end
end
bef=i;
for j=bef:-1:1
if SN(order(j)).cond==1
break;
end
end
SN(order(j)).closest=order(l);
SN(order(l)).prev=order(j);
SN(order(j)).dis=sqrt((SN(order(l)).x-SN(order(j)).x)^2 + (SN(order(l)).y-
SN(order(j)).y)^2);
SN(order(l)).dis2=SN(order(j)).dis;
end
operating_nodes=operating_nodes-1
dead_nodes=dead_nodes+1;
SN(order(i)).closest=0;
SN(order(i)).prev=0;
SN(order(i)).dis=0;
SN(order(i)).dis2=0;
SN(order(i)).pos=101;
SN(order(i)).rop=rnd;
end
end
if operating_nodes<n && temp_val==0
temp_val=1;
flag1stdead=rnd;
end
rnd=rnd+1
turn=turn+1;

op(rnd)=operating_nodes;

if energy>0
nrg(rnd)=energy;
end
end
sum=0;
for i=1:flag1stdead
sum=nrg(i) + sum;
end
temp1=sum/flag1stdead;
temp2=temp1/n;
for i=1:flag1stdead
avg_node(i)=temp2;
end

Output:
Experiment No. 6
Aim: Implementation of DSDV Routing Protocol on MATLAB

Code:
clc;
clear all;
disp('Distance vector routing protocol');
node=input('Enter the no. of nodes: ');
over=0;
for i=1:node %initialize
for j=i:node
if(i==j)
matrix(i,j)=0;
else
matrix(i,j)=randi(1,1);
matrix(j,i)=matrix(i,j);
end
end
end
disp(matrix);

i=1;
x=1;
mat1=triu(matrix);
for i=1:node
for j=1:node
if(mat1(i,j)~=0)
mat(i,j)=x;
mat(j,i)=mat(i,j);
x=x+1;
end
end
end
disp(mat1);

G = digraph(mat1);
plot(G,'Layout','force');

for from=1:node% fill initial matrix with via = to


for via=1:node
for to=1:node
if(from~=via&&from~=to)
if(via==to&&matrix(from,to)~=0)
go(to,via,from)=matrix(from,to);
else
go(to,via,from)=100;
end
else
go(to,via,from)=inf;
end
end
end
end
i=0;
while(i<2)
for from=1:node
for to=1:node
if(from~=to)
if(matrix(from,to)~=0)%calculate neighbour node
for x=1:node
for y=1:node
temp(x,y)=matrix(from,to)+min(go(y,:,to));
if(temp(x,y)<go(y,to,from)&&go(y,to,from)<inf)
go(y,to,from)=temp(x,y);
end
end
end
end
end
end
end
i=i+1;
end
disp(go);
choice='y';
while(choice=='y')
source=input('Enter the source node: ');
dest=input('Enter the destination node: ');
trace(1)=source;
j=2;
while(source~=dest)
[row,col]=find(go(dest,:,source)==min(go(dest,:,source)));
trace(j)=col;
source=col;
j=j+1;
end
k=1:j-1;
disp(trace(k));

choice=input('Do you want to try again (y/n):','s');


end

Output:
Experiment No. 7
Aim: Implementation of AODV Routing Protocol on MATLAB
Code:
%Code : AODV Routing.
x=1:20;
s1=x(1);
d1=x(20);
clc;
A=randi(20,20);
% Making matrix all diagonals=0 and A(i,j)=A(j,i),i.e. A(1,4)=a(4,1),
% A(6,7)=A(7,6)
for i=1:20
for j=1:20
if i==j
A(i,j)=0;
else
A(j,i)=A(i,j);
end
end
end
disp(A);
t=1:20;
disp(t);

disp(A);
status(1)='!';
% dist(1)=0;
dist(2)=0;
next(1)=0;

for i=2:20
status(i)='?';
dist(i)=A(i,1);
next(i)=1;
disp(['i== ' num2str(i) ' A(i,1)=' num2str(A(i,1)) ' status:=' status(i) ' dist(i)=' num2str(dist(i))]);
end
flag=0;
for i=2:20
if A(1,i)==1
disp([' node 1 sends RREQ to node ' num2str(i)])
if i==20 && A(1,i)==1
flag=1;
end
end
end
disp(['Flag= ' num2str(flag)]);
while(1)
if flag==1
break;
end
temp=0;
for i=1:20
if status(i)=='?'
min=dist(i);
vert=i;
break;
end
end
for i=1:20
if min>dist(i) && status(i)=='?'
min=dist(i);
vert=i;
end
end
status(vert)='!';
for i=1:20
if status()=='!'
temp=temp+1;
end
end
if temp==20
break;
end
end
i=20;
count=1;
route(count)=20;
while next(i) ~=1
disp([' Node ' num2str(i) 'sends RREP message to node ' num2str(next(i))])
i=next(i);
%disp(i);
count=count+1;
route(count)=i;
route(count)=i;
end
disp([ ' Node ' num2str(i) 'sends RREP to node 1'])
disp(' Node 1 ')
for i=count: -1:1
disp([ ' Sends message to node ' num2str(route(i))])
end

Output:
Experiment No. 8
Aim: Implementation of any one Flooding Protocol on MATLAB
Code:
%=====================================================================
===
% Mobile Ad-hoc Networks
% Optimized Link State Routing (OLSR) protocol
% Iterative algorithm for selecting Multipoint Relays (MPRs)
%=====================================================================
===
% Clearing
clc;
clear all;
close all;

total_nodes = 10; % total number of nodes


node_ids = 1:total_nodes; % array to store node IDs (1 x total)
%% Create a randomly-connected network
attempts_threshold = 100; % threshold to stop creation attempts
created_flag = 0; % indicate creation of a connected network
exit_flag = 0; % indicate failure in creating the network
attempts = 0; % count number of attempts
while (created_flag == 0)
% call function createConnectedNetwork
[G, created_flag] = createConnectedNetwork (total_nodes);
% increment count of attempts
attempts = attempts + 1;
% Check if threshold reached and network is not created
if ((attempts >= 100) && (created_flag == 0))
% set exit flag
exit_flag = 1;
% break from while loop
break;
end % end if
end % end while
% Check if exit flag is set
if (exit_flag == 1)
% If exit flag set, display a message and exit the program
disp ('Cannot create a connected network graph');
disp ('Try changing the decision_threshold in the createConnectedNetwork method');
disp ('Program stopped');
else
%% Sample mpr selector, extract first-hop and second-hop neighbors
% If a connected network was created, continue
disp (strcat('A connected network was created with number of attempts = ',int2str(attempts)));
% Select the MPR selector node (randomly)
mpr_selector = datasample(node_ids, 1);
disp (strcat('MPR selector node: ', int2str(mpr_selector)));
% Get the first-hop and second-hop neighbors of the MPR selector node
[firstHop_ids, secondHop_ids] = get_First_Second_Neighbors(mpr_selector, G);
disp ('First-hop neighbors:');
disp (firstHop_ids');
disp ('Second-hop neighbors:');
disp (secondHop_ids);
% Check if the mpr selector has second-hop neighbors
if (isempty(secondHop_ids))
disp ('No second-hop neighbors exist');
disp('try re-creating the network');
disp('Program stopped');
else
%% Start MPRs selection algorithm
% Define empty array to store the selected MPRs
selected_MPRs = [];
% 1- Detect second-hop neighbors that are connected to a single
% first-hop neighbor only
for i=1:length(secondHop_ids)
% call function getIncludedNeighbors
[included, count_included] = getIncludedNeighbors(secondHop_ids(i), G,firstHop_ids);
if ((count_included == 1) && (~ismember(included(1), selected_MPRs)))
% append the first-hop neighbor to the selected MPRs
selected_MPRs = [selected_MPRs, included];
end % end if
end % end for
% Set available first-hop ids
available_firstHop = firstHop_ids;
if (~isempty(selected_MPRs))
disp ('selected MPRs in step 1:');
disp (selected_MPRs);
% Remove selected MPRs from available first-hop neighbors
selected_ids= ismember(available_firstHop, selected_MPRs);
available_firstHop(selected_ids)=[];
else
disp ('No MPRs selected in step 1');
end % end if
% if all first-hop neighbors were selected, no need to continue
if (isempty(available_firstHop))
disp('All first-hop neighbors were selected in step 1');
disp('Program stopped');
else
disp ('First-hop neighbors available for selection:');
disp (available_firstHop');
%% 2- Add additional MPRs based on coverage criteria
% update uncovered second-hop ids
uncovered_secondHop = secondHop_ids;
if (~isempty(selected_MPRs))
for i=1:length(selected_MPRs)
m = selected_MPRs(i);
% get what does the mpr covers from the uncovered set
[temp, count_temp] = getIncludedNeighbors(m, G, uncovered_secondHop);
% update the uncovered second-hop set
ids= ismember(uncovered_secondHop, temp);
uncovered_secondHop(ids)=[];
end % end for
end % end if
if (isempty(uncovered_secondHop))
disp('All second-hop neighbors are covered');
disp('Program stopped');
else
disp('uncovered second-hop neighbors');
disp(uncovered_secondHop);
% While still some second-hop neighbors are uncovered
while (~isempty(uncovered_secondHop))
disp('selecting the first-hop neighbor with max coverage');
% 1- Select the first-hop neighbor with max coverage
[selected_node, covered_nodes] =
getNodeMaxCoverage(available_firstHop,uncovered_secondHop, G);
% 2- Append the selected node to selected MPRs
selected_MPRs = [selected_MPRs, selected_node];
disp ('selected MPRs changed to:');
disp (selected_MPRs);
% 3- Update the remaining first-hop neighbors
idx= ismember(available_firstHop, selected_MPRs);
available_firstHop(idx)=[];
% 4- Update the uncovered set of second hop neighbors
ids= ismember(uncovered_secondHop, covered_nodes);
uncovered_secondHop(ids)=[];
disp ('Uncovered second-hop neighbors changed to:');
disp (uncovered_secondHop);
end % end while
end % end if
end %end if
% Display the result (selected MPRs)
disp('Overall Selected MPRs:');
disp(selected_MPRs);
% Calculate and display the saving due to the algorithm
saving = length(firstHop_ids) - length(selected_MPRs);
disp('First-hop nodes used for broadcasting decreased by:');
disp(saving);
disp ('end');
% Draw the graph highliting MPR selector, first,second-hop neighbors, and selected MPRs
title_s = 'MPR Selector (Red), First-hop (Green), Second-hop (Black), selected
MPRs(Yellow)';
%% Plot graph
% set figure to full screen
figure('units','normalized','outerposition',[0 0 1 1])
% plot graph
h = plot(G);
% Highlight MPR selector node with red color
highlight(h, mpr_selector, 'NodeColor', 'r');
% Highlight first-hop neighbors with green color
highlight(h, firstHop_ids,'NodeColor', 'g');
% Highlight second-hop neighbors with black color
highlight(h, secondHop_ids,'NodeColor', 'k');
% Highlight selected MPRs with yellow color
highlight(h, selected_MPRs,'NodeColor', 'y');
% set the title
title(title_s);
end % end if
end % end if

%=====================================================================
=====
% Create an adjacency matrix and a connected network graph
% Input: Total number of nodes
% Output: Graph and status flag
%=====================================================================
=====
function [G, connected] = createConnectedNetwork(N)
% threshold for decision on connectivity (0 < decision_threshold < 1)
decision_threshold = 0.5;
% Connect nodes randomly
% 1- Define empty matrix (NxN)
A = zeros(N,N);
% 2- Fill adjacency matrix based on a random condition
for i= 1:N % Loop in rows
for j= 1:N % Loop in columns
if (j>i) % if not diagonal and upper
x= rand; % Generate random number between 0 and 1
if (x>=decision_threshold)
A(i,j)= 1; % Assign a relation
end % end if
end % end if upper
end % end for columns
end % end for rows
% 3- Create graph using the upper part of the adjacency matrix
G= graph(A,'upper');
% 4- Check if all nodes are connected to each other
k = dfsearch(G,1); % starting from node 1, get the IDs of connected nodes
if (length(k) == N) % check if the number of connected nodes equals N
connected = 1; % if true, all nodes are connected
else
connected = 0; % else, not all nodes are connected
end % end if
end % function createConnectedNetwork
%=====================================================================
====
% Get the node that has maximum coverage of a reference list
% Input: array of candidates, refernce list
% Output: node with max coverage, covered nodes
%=====================================================================
====
function [node_maxCoverage, covered_set] = getNodeMaxCoverage(candidates, reference,graph)
maxCovereage = 0;
covered_set = [];
% loop into canditaties and get the node with max coverage
for i=1:length(candidates)
[covered, count_covered] = getIncludedNeighbors(candidates(i), graph, reference);
if (count_covered > maxCovereage)
maxCovereage = count_covered;
node_maxCoverage = candidates(i);
covered_set = covered;
end
end %end for
end %end function getNodeMaxCoverage

%=====================================================================
====
% Get the neighbors of a node that are included in a reference list
%=====================================================================
====
function [matched_neighbors, count_matched] = getIncludedNeighbors(node, graph,referenceList)
% 1- Get the neighbors of the input node
neighbors_n = neighbors(graph, node);
% 2- Get the included neighbors and count them
matched_neighbors = intersect(neighbors_n, referenceList);
count_matched = length(matched_neighbors);
end % end function getIncludedNeighbors

%=====================================================================
====
% Get the first-hop and second-hop neighbors of a node
% Input: index of a node, graph
% Output: array of first-hop neighbors, array of second-hop neighbors
%=====================================================================
====
function [firstHop_neighbors, secondHop_neighbors] = get_First_Second_Neighbors(node,graph)
% 1- Get the set of first-hop neighbors of the node
firstHop_neighbors = neighbors(graph, node);
% 2- Get the second-hop neighbors of the node
secondHop_neighbors = [];
for i=1:length(firstHop_neighbors)
% get neighbors of each first hop neighbor
temp_secondHop_neighbors = neighbors(graph, firstHop_neighbors(i));
% check if each neighbor can be added to the second-hop neighbors
for j=1:length(temp_secondHop_neighbors)
x = temp_secondHop_neighbors(j);
if ((~ismember(x, firstHop_neighbors)) && (x~=node)
&&(~ismember(x,secondHop_neighbors)))
% append to the list of second-hop neighbors
secondHop_neighbors = [secondHop_neighbors, x];
end % end if
end % end for
end % end for
end %end function get_First_Second_Neighbors

Output:

You might also like