LEACH协议的MATLAIB仿真代码

合集下载

基于MATLAB的HDLC协议CRC算法仿真

基于MATLAB的HDLC协议CRC算法仿真

基于MATLAB的HDLC协议CRC算法仿真作者:陈晓宇来源:《中国新通信》2013年第15期【摘要】HDLC协议广泛的应用于网络,无线传输及工业控制中,对于HDLC协议中帧校验FCS的算法,由于子协议的不同和芯片厂家的差异,导致变化多样,很容易混淆。

本文分析了HDLC协议中帧校验FCS的计算原理及基本算法,之后列举了各种常见的变化算法,使用matlab作为仿真工具,对计算方法和计算结果进行了验证。

【关键词】HDLC,MatlabCRC算法仿真七十年代初期,IBM公司率先提出了面向比特的同步数据链路控制规程SDLC(Synchrous Data Link Control),随后,国际标准化组织ISO采纳并发展了SDLC,并分别提出了自己的标准,即高级数据链路控制规程HDLC(High-level Data Link Control)。

HDLC的特点:协议不依赖于任何字符编码集;数据报文透明传输;全双工通信,有较高的数据链路传输效率;所有帧均采用CRC校验,传输可靠性高,目前网络设计普遍使用HDLC作为数据链路管制协议[1]。

实施HDLC的一般方法通常是采用ASIC器件和软件编程等,但由于HDLC标准的文本较多,ASIC芯片出于专用性的目的难以通用于不同版本,缺乏应用灵活性。

例如CCITT、ANSI、ISO/IEC等都有各种版本的HDLC标准,器件生产商都还有各自的标准,对HDLC的CRC序列生成多项式等有不同的规定[2]。

本文重点分析了HDLC中CRC的计算原理,给出了众多规定下的各种CRC算法及matlab 仿真,明确了之间的区别和使用方法,并比较了使用硬件和软件计算CRC的各自优势及应用场景选择。

一、HDLC帧结构与CRC校验HDLC规程主要由帧结构、规程要素、规程类别三个部分组成[3]。

HDLC的帧结构在不同的标准下长度不一,但基本结构相同,图1表示出了ISO/IEC 3309标准规定的HDLC的基本帧结构[4]。

基于LEACH路由的分簇算法研究

基于LEACH路由的分簇算法研究

• 73•作为无线传感器网络的重要技术,WSN 路由协议是学术研究的热门话题。

LEACH 协议作为典型的的分簇算法它有很多的优点,但也有不足之处。

本文首先分析了原始的LEACH 算法。

缺点是没有考虑节点的剩余能量和位置。

在本文中,改进了缺陷,并将剩余的能量添加到考虑标准中,并且还增加了簇头之间的距离以避免形成热区域和簇头分布太密集。

通过Matlab 仿真,验证了改进的LEACH 算法可以使簇头分布更均匀,更能节省能耗,提高了网络生命周期。

1 LEACH协议LEACH (Low Energy Adaptive Clustering Hierarchy )全称是“低能耗自适应分簇型路由算法”,它是一种基于LEACH 协议的算法,因此被称作LEACH 算法,它作为层次型分簇路由算法,是无线传感器中很典型的代表(柳丽娜,无线传感器网络中LEACH 算法的研究和改进:吉林大学,2012)。

第一步,节点的初始化;第二步,选出网络中的簇头节点;第三步,正常部分成为簇头之后的初始化(基站的初始化,公共传感器节点的能量等),属于网络的建立阶段,并且选择簇头是在随机过程中生成的。

然后网络稳定来进行数据传输。

这属于一个循环,然后来回循环直到能量耗尽。

其中在选择簇头的过程中,首先会产生0到1的随机数值,如果产生的此数值比T(n)大,那么该节点就被选为簇首,T(n)就作为能否当选为簇头的标准。

T(n)的表达式为:(1)其中:P 是选举的簇头比例;r 是此时正在进行的轮数;G 是此时还没当选簇头的节点集合。

2 LEACH协议不足在分析了经典的LEACH 分簇算法过程中,虽然优点很多,但也存在一些缺点(唐甲东,蔡明,无线传感器网络路由协议研究-LEACH 路由协议的改进:计算机工程,2013):(1)簇头很容易产生在一些能量很低的节点上,从而会大大降低网络的寿命。

(2)簇头节点分布不均匀,有些过于集中,因此能量不能达到均衡状态。

激光仿真matlab代码

激光仿真matlab代码

条形平面镜:function tiaoxing(bochang,N,m,L,handles)global nglobal pointk=2*pi/bochang;a=m*1e+006;deltax=2*a/point;%取单位长度xx=-a:deltax:a;L=L*1e+006;nn=length(xx);u=ones(1,nn);jj=1:nn;for n=1:N %进行迭代for b=1:nnuu(b)=sqrt(i*exp(-i*k*L)/(bochang*L)).*...sum(exp(-i*k*((b-jj)*deltax).^2./(2*L)).*u)*deltax;%endma=max(uu);%归一化uu=uu./ma;u=uu;axes(handles.axes1);plot(xx,abs(u))axes(handles.axes2);plot(xx,angle(u))set(handles.edit10,'string',num2str(n));%迭代次数显示到面板end方形平面镜:function juxing(bochang,a,b,L,N,handles)global nglobal pointk=2*pi/bochang;a=a*1000000;b=b*1000000;deltax=2*a/point;min=0.09;L=L*1000000;xx=-a:deltax:a;%取单位长度yy=-b:deltax:b;nx=length(xx);ny=length(yy);ux=ones(1,nx);uy=ones(1,ny);u_last=ones(ny,nx);u_next=ones(ny,nx);jx=1:nx;jy=1:ny;for n=1:Nfor mx=1:nx %x方向迭代uux(mx)=sqrt(i*exp(-i*k*L)/(bochang*L)).*...sum(exp(-i*k*((mx)*deltax-(jx)*deltax).^2./(2*L)).*ux)*deltax;% endux=uux;for my=1:ny %y方向迭代uuy(my)=sqrt(i*exp(-i*k*L)/(bochang*L)).*...sum(exp(-i*k*((my)*deltax-(jy)*deltax).^2./(2*L)).*uy)*deltax;% for o=1:nx %两个方向逐个相乘u_next(my,o)=ux(o).*uuy(my);endenduy=uuy;%归一化处理ma=max(max(u_next));u_next=u_next./ma;u_last=u_next;axes(handles.axes1);[XX,YY]=meshgrid(xx,yy);mesh(XX,YY,abs(u_last));axes(handles.axes2);mesh(XX,YY,angle(u_last));set(handles.edit10,'string',num2str(n));%迭代次数显示到面板shading flat;end圆形平面镜:function circle(a,L,b,diedai,handles)global pointglobal nN=point;a=a*1000000;L=L*1000000;uu=ones(N,1);%初始化u=ones(N,1);k=2*pi/b;m=1:N;dr=a/(N-1);da=2*pi/(N-1);r=dr*(m-1);%离散化theta=da*(m-1);for n=1:diedai %进行迭代for j=1:Nu(j)=sum(exp(-i*k*L)*exp(-i*k*(r(j)^2+(r.^2)')/(2*L)).*r'.*(exp(i*k*r(j)*r'*…cos(theta)/L)*da*ones(N,1)).*uu);endma=max(u);%归一化uu=u/ma;axes(handles.axes1);mesh(r'*cos(theta),r'*sin(theta),abs(uu)*ones(N,1)')shading interpaxes(handles.axes2);mesh(r'*cos(theta),r'*sin(theta),angle(uu)*ones(N,1)')set(handles.edit10,'string',num2str(n));%将迭代次数显示在面板上shading interpend。

LEACH协议和SEP协议模型

LEACH协议和SEP协议模型

目录前言 (1)第1章概述 (2)1.1研究目的及意义 (2)1.1.1 研究目的 (2)1.1.2 研究意义 (2)1.2 无线传感器网络概述 (3)1.2.1 无线传感器网络模型 (3)1.2.2 无线传感器的结构 (5)1.2.3 无线传感器网络的相关应用 (5)1.2.4 无线传感器网络的研究现状 (6)1.3运行平台MATLAB的概述 (7)第2章无线传感器网络路由协议 (9)2.1无线传感器网络路由协议 (10)2.2WSN成簇算法 ......................................................................................... .102.2.1 成簇算法基本概念 (10)2.2.2 成簇算法基本目标及其性能评价 (12)2.2.3. 基于分簇的MAC协议 (12)2.2.4 成簇算法之LEACH (13)2.2.5 成簇算法之SEP (17)第3章仿真实现LEACH协议和SEP协议模型 (18)3.1无线传感器网络仿真方法 (18)3.2仿真环境假设和参数设置 (18)3.3LEACH协议仿真模型的建立 (19)3.3.1 变量的定义 (19)3.3.2 随机的建立一个无线传感器网络 (19)3.3.3 仿真网络运行的主循环 (20)3.3.4 数据和仿真曲线的导出 (21)3.4SEP协议仿真模型的建立 (22)3.4.1变量的定义 (22)3.4.2 随机的建立一个无线传感器网络 (22)3.4.3 仿真网络运行的主循环 (23)3.4.4 数据和仿真曲线的导出 (25)第4章 LEACH协议和SEP协议仿真结果分析 (26)4.1仿真分析指标 (26)4.2LEACH协议的仿真结果分析 (26)4.3SEP协议的仿真结果分析 (30)4.4LEACH和SEP的仿真结果比较分析 (33)第5章结论 (35)5.1主要工作 (35)5.2毕业设计中解决的问题 (35)5.3设计心得 (36)致谢 (37)参考文献 (38)。

matlab信道仿真经典源程序

matlab信道仿真经典源程序

matlab信道仿真经典源程序% %% Rayleigh Fading Channel Signal Generator% Using the Dent Model (a modification to the Jakes Model) %% Last Modified 10/18/05 %% Author: Avetis Ioannisyan (avetis@) % %% Usage:% [omega_mTau, Tk] =% ai_RayCh(NumAngles, Length, SymbolRate, NumWaveforms, CarrierFreq, Velocity) %% Where the output omega_mTau is a time scaling factor for plotting% normalized correlations. The LAGS value output by [C,LAGS] = XCORR(...) % should be multiplied by the omega_mTau scaling factor to properly display % axis. Tk is a two dimensional vector [M, N] = SIZE(Tk) with% M=numWaverorms and N=Length specified in the RayCh(...) function call %% And the input variables are: %% NumAngles - scalar power of 2, NumAngles > 2^7 is used to specify the % number of equally strong rays arriving at the receiver. It used to% compute the number of oscillators in the Dent model with N0 =numAngles/4 %% Length - scalar preferably power of 2 for faster computation, Length >2^17 % is used to specify the length of the generated sequence. Lengths near1E6 % are close to realistic signals %% SymbolRate - scalar power of 2 and is in kilo-symbols-per-sec is usedto % specify what should be the transmission data rate. Slower rates will % provide slowly fading channels. Normal voice and soem data rates are % 64-256 ksps %% NumWaveforms - scalar used to specify how many 'k' waveforms to generate % in the model. NumWaveforms > 2 to properly display plots %% CarrierFreq - scalar expressed in MHz is the carrier frequency of the % tranmitter. Normally 800 or 1900 MHz for mobile comms %% Velocity - scalar expressed in km/hr is the speed of the receiver. % 100 km/hr = 65 mi/hr. Normal values are 20-130 km/hr %% Usage Examples:% [omega_mTau, Tk] = ai_RayCh(2^7, 2^18, 64, 2, 900, 100) %% where %% NumAngles=2^7, Length=2^18, symbolRate=64, NumWaveforms=2,carrierFreq=900, Velocity=100% [omega_mTau, Tk] = RayCh(NumAngles, Length, symbolRate, NumWaveforms, % carrierFreq, Velocity); % %function [omega_mTau, Tk] = ai_RayCh(NumAngles, Length, symbolRate, NumWaveforms, carrierFreq, Velocity)% Number of oscillators N0 = NumAngles/4;% Maximum Doppler shift of carrier at some wavelength omega_m = (2*pi) * fm(Velocity, carrierFreq); % specify variance of the Rayleigh channel% use this for *constant* variange - requires changing other params in prog sigma2 = 10;% make sigma2 a gaussian RV around u = sigma2 and var = sigma2/5% use for *non constant* variaance - requires changing other params in prog sigma2 = sigma2 + sqrt(sigma2/5) .* randn(1,NumWaveforms); % Initialize phasesalpha_n = []; beta_n = []; theta_nk = []; % make a hadamard matrix Ak = hadamard(N0);% determine phase values 'alpha' and 'beta' n=[1:N0];alpha_n = 2*pi*n/NumAngles - pi/NumAngles; beta_n = pi*n/N0;% convert to time scale using 'fs' sampling frequencyt=[1/(symbolRate*1000):1/(symbolRate*1000):1/(symbolRate*1000) * Length];Tk = [];for q = 1 : NumWaveformsrand('state',sum(100*clock)) % reset randomizertheta_nk = rand(1,length(n)) * 2 *pi; % create uniform random phasein range [0,2pi]sumRes = 0; for i = 1 : N0term1 = Ak(NumWaveforms,i);term2 = cos(beta_n(i)) + j*sin(beta_n(i));term3 = cos(omega_m .* t .* cos(alpha_n(i)) + theta_nk(i)); sumRes = sumRes + (term1 .* term2 .* term3); endTk(q,:) = sqrt(2/N0) .* sumRes;% use line below to apply *non-constant* varianceTk(q,:) = repmat(10.^(sigma2(q)/20),1, Length) .* Tk(q,:); %apply variable in dB end% apply *constant* variance unilaterly in dB % Tk = repmat(10^(sigma2/20), k, Length) .* Tk;% plot resultsfigure(20); subplot(3,1,1); semilogy(t,abs(Tk(1,:))); xlabel('Time (sec)'); ylabel('Signal Strength (dB)');title(['Received Envelope, Symbol Rate = ', num2str(symbolRate), ',Carrier = ', num2str(carrierFreq), ', Velocity = ', num2str(Velocity)]); % computeauto and cross correlations and plot themomega_mTau = (1/(symbolRate*1000)) * (omega_m/(2*pi)); % computeomega_m * tau scaling[C1, Lags] = crosscorr(Tk(1,:), Tk(2,:), 20000); [C2, Lags2] =autocorr(Tk(1,:), 20000);figure(20); subplot(3,1,3); plot(Lags * omega_mTau, C1);xlabel('Normalized Time Delay'); ylabel('Normalized Crosscorrelation'); title('Crosscorrelation between waveforms k=1 and k=2'); figure(20);subplot(3,1,2); plot(Lags2 * omega_mTau, C2);xlabel('Normalized Time Delay'); ylabel('Normalized Autocorrelation'); title('Autocorrelation of the first waveform k=1');感谢您的阅读,祝您生活愉快。

matlab扩频通信仿真代码

matlab扩频通信仿真代码

《MATLAB扩频通信仿真代码探究》一、概述MATLAB是一种功能强大的数学软件工具,广泛应用于科学和工程领域。

扩频通信是一种在通信系统中应用较多的技术,能够提高通信系统的安全性和抗干扰性。

本文将就MATLAB中扩频通信仿真代码进行探究,以了解其原理和实现。

二、扩频通信技术简介扩频通信是通过在发送端用高速码对数据进行调制,从而增大信号带宽,提高信噪比,以实现更可靠的数据传输。

在接收端,可以利用相同的高速码进行解调,将信号还原为原始数据。

扩频通信技术包括直接序列扩频(DSSS)和正交频分复用(OFDM)等多种方式。

三、MATLAB中的扩频通信仿真代码在MATLAB中,可以利用其丰富的工具箱和函数库,快速实现扩频通信系统的仿真。

通过编写相应的代码,可以模拟扩频通信系统中的传输、接收、信道建模等过程,对系统性能进行评估和优化。

我们需要定义扩频序列,可以选择PN序列或者其他扩频序列。

在发送端,利用扩频序列对数据进行调制,形成扩频信号。

接下来,在信道模型中加入噪声和干扰,模拟真实通信环境。

在接收端,利用相同的扩频序列进行解调,将信号恢复为原始数据。

通过仿真可以得到系统的误码率、传输速率、抗干扰性等性能参数,对系统进行优化和改进。

四、个人观点和理解扩频通信技术在现代通信系统中起着重要作用,其在军事通信、无线网络、卫星通信等领域有着广泛的应用。

利用MATLAB的强大功能,可以快速进行扩频通信系统的仿真和分析,为工程实践提供重要参考。

通过深入学习和探究MATLAB中的扩频通信仿真代码,可以更好地理解扩频通信技术的原理和实现方法,为相关领域的研究和开发提供有力支持。

在总结回顾本文内容时,我们了解了MATLAB中扩频通信仿真代码的实现原理和应用。

通过对扩频通信技术的深入学习和实践,可以更好地掌握通信系统的设计和优化方法,为信息通信领域的发展贡献力量。

总结:通过对MATLAB扩频通信仿真代码的探究,我们深刻理解了扩频通信技术的原理和实现方法,并认识到MATLAB在通信系统仿真中的重要作用。

密勒码仿真及代码

密勒码定义密勒码也称延迟调制码,是一种变形双向码。

源程序代码library ieee;use ieee.std_logic_1164.all;use ieee.std_logic_unsigned.all;use ieee.std_logic_arith.all;entity mile isport(m_sel:in std_logic_vector(1 downto 0);clk: in std_logic;data_clk:buffer std_logic;mcst_out,REF_CLK,ref_clk2:buffer STD_LOGIC;miller_out,data:out std_logic);end;architecture one of mile issignal dout1:std_logic_vector(6 downto 0);signal q :std_logic;signal q1:std_logic;signal q2:std_logic;signal q3:std_logic;begincom1:process(clk,data_clk)beginif data_clk'event and data_clk='1' thencase m_sel iswhen"00"=>if dout1(2 downto 0)="000"then dout1(0)<='1';else dout1(1 downto 0)<=dout1(2 downto 1);dout1(2)<=dout1(0) xor dout1(1);end if;when"01"=>if dout1(3 downto 0)="0000"then dout1(0)<='1';else dout1(2 downto 0)<=dout1(3 downto 1);dout1(3)<=dout1(0) xor dout1(1);end if;when"10"=>if dout1(5 downto 0)="000000" then dout1(0)<='1'; else dout1(4 downto 0)<=dout1(5 downto 1);dout1(5)<=dout1(0) xor dout1(1);end if;when"11"=>if dout1="0000000" then dout1(0)<='1';else dout1(5 downto 0)<=dout1(6 downto 1);dout1(6)<=dout1(0) xor dout1(1);end if;when others=>null;end case;end if;end process com1;com2:process(clk)beginif clk'event and clk='1' thenq<=not q;data_clk<=q;end if;end process com2;com3:process(data_clk)beginif dout1(0)='1' thenq1<=data_clk;elseq1<=not data_clk;end if;ref_clk2<=q1;end process com3;com4:process(mcst_out)beginif mcst_out'event and mcst_out='0'thenq3<=not q3;end if;miller_out<=q3;end process com4;com5:process(clk,data_clk)beginif clk'event and clk='1' thenmcst_out<=ref_clk2;data<=dout1(0);ref_clk<=data_clk;end if;end process com5;end one;5.4 仿真图3级M序列输出4级M序列输出6级M序列输出7级M序列输出。

利用MATLAB仿真创新网络演化过程的程序及其说明

第一部分程序:获取不同δ值时的网络演化情况并保存成数据文件clear all;clc;N_delta_array = 4;Array_delta = [0.0005,0.001,0.0015,0.0025];for nda = 1:N_delta_array%% %%%%% Initial parametersn0 = 20; %initial number of pointsT = 3000; %total number of steps needed runningm2 = 10; %number of new links for each new points p_ini = 0.5; %probability of initial linksp_iso = 0.01; %probability of isolate point to be selectedp_sat = 0.0002; %probability of saturated point to be selecteddelta = Array_delta(nda); %factor of increasing resource %% %%%%% Get initial total numberN = n0; %initial total number of points%% %%%%% Prepare empty arrays to save informationti = zeros(N,1); %typelij = zeros(N,N); %linkki = zeros(N,1); %degreemi = zeros(N,1); %resourcepij = zeros(N,N); %performancewij = zeros(N,N); %weight%%%%%%%%%%%%%%%%%isolate = zeros(N,1); %isolate statesaturation = zeros(N,1); %saturated stateEgt = zeros(T,1); %efficiency of cooperationDgt = zeros(T,1); %variance of cooperate efficiencyLt = zeros(T,1); %average lengthZt = zeros(T,1); %aggregation factorKt = zeros(T,1); %average degree of netVt = zeros(T,1); %variance of Ktlt = zeros(T,1); %max(ki)-min(ki)ut = zeros(T,1); %average of the differenceSt = zeros(T,1); %number of sizes at each step%% %%%%% Initialization befor the first step%% %%%%%%%%%%%%%%%% Initialize types of each points for nti = 1:Nti(nti) = fix(4*rand(1,1))+1;if ti(nti) == 4ti(nti) = 2;endend%% could or n't be connectedcould_cot = zeros(N,N);for ni = 1:Nfor nj = 1:Nif (ni~=nj)&&((ti(ni)~=ti(nj))||((ti(ni)==2)&&(ti(nj)==2)))could_cot(ni,nj) = 1;endendendcould_cot_ini = could_cot;%% %%%%%%%%%%%%%%%% Initialize linkspor_i = rand(1,N);tempones = ones(1,N);key_lij = meshgrid(por_i,tempones)+meshgrid(por_i,tempones)'; key_lij = key_lij.*could_cot;idx_ini = find(key_lij>2*(1-p_ini));lij(idx_ini) = 1;could_cot = could_cot-lij;%% %%%%%%%%%%%%%%%% Initialize weights tempw = rand(1,N)*5*T;wij = (meshgrid(tempw,tempones)+meshgrid(tempw,tempones)').*lij;%% %%%%%%%%%%%%%%% Initialize degreeski = sum(lij)';%% %%%%%%%%%%%%%%%% Initialize resourcesmi = rand(N,1);%% %%%%%%%%%%%%%%%% Initialize resourcespij = zeros(N,N);%% %%%%%%%%%%%%%%%%%%% step by step runningfor nt = 1:Tdisp(['Step',num2str(nt),' is running']);%% delete the connectionwij = wij-1;idx_lost = find(wij<=0);wij(idx_lost) = 0;lij(idx_lost) = 0;could_cot(idx_lost) = 1;could_cot = could_cot.*could_cot_ini;ki = sum(lij)';%% delete the isolated pointstate_temp = (1-isolate).*(1-saturation);idx_state = find(state_temp==0);kitemp = ki;kitemp(idx_state) = 10^4;idx_isolate = find(kitemp==min(kitemp));key_isolate = zeros(N,1);key_isolate(idx_isolate) = 1;key_isolate = key_isolate.*rand(N,1);key_isolate = ones(N,1)-key_isolate;idx_chk = find(key_isolate<p_iso);isolate(idx_chk) = 1;ki(idx_chk) = 0;lij(idx_chk,:) = 0;lij(:,idx_chk) = 0;wij(idx_chk,:) = 0;wij(:,idx_chk) = 0;could_cot(idx_chk,:) = 0;could_cot(:,idx_chk) = 0;could_cot_ini(idx_chk,:) = 0;could_cot_ini(:,idx_chk) = 0;%% mark the saturation pointstate_temp = (1-isolate).*(1-saturation);temp_sat = rand(N,1).*state_temp;idx_sat = find(temp_sat>(1-p_sat));saturation(idx_sat) = 1;could_cot(idx_sat,:) = 0;could_cot(:,idx_sat) = 0;could_cot_ini(idx_sat,:) = 0;could_cot_ini(:,idx_sat) = 0;%% add new connectionsm1 = fix(0.02*N);number_codcot = sum(sum(could_cot))/2;if number_codcot <= m1lij = lij+could_cot;meshtemp = meshgrid(rand(1,N),ones(1,N));wij = wij+5*T*could_cot.*(meshtemp+meshtemp');could_cot = zeros(N,N);elseKIM = meshgrid((ki+1).*mi,ones(1,N));KIMS = KIM+KIM';OP = could_cot.*KIMS.*tril(ones(N,N),0);OPL = reshape(OP,1,N*N);COPL = cumsum(OPL);COP = reshape(COPL,N,N);keynew = m1;while keynew >0keyone = rand(1,1)*COP(N,N);IKA = find(COPL>keyone);IK = IKA(1);KEY = COPL(IK);idx_new1 = find(COP==KEY);idx_new2 = find(COP'==KEY);if could_cot(idx_new1)==1lij(idx_new1) = 1;lij(idx_new2) = 1;could_cot(idx_new1) = 0;could_cot(idx_new2) = 0;wij(idx_new1) = rand(1,1)*10*T;wij(idx_new2) = wij(idx_new1);keynew = keynew-1;endendend%% add new pointN = N+1;ti_temp = ti;ti = [ti;0];ti(N) = fix(4*rand(1,1))+1;if ti(N) == 4ti(N) = 2;endmi = [mi;rand(1,1)];isolate = [isolate;0];%isolate statesaturation = [saturation;0];%saturated stateki = [ki;0];%% could connectedcould_cot = [could_cot;zeros(1,(N-1))];could_cot = [could_cot,zeros(N,1)];could_cot_ini = [could_cot_ini;zeros(1,(N-1))]; could_cot_ini = [could_cot_ini,zeros(N,1)];cd_N = zeros(1,N-1);if ti(N)==2could_cot(N,:) = ones(1,N);could_cot(:,N) = ones(N,1);could_cot_ini(N,:) = ones(1,N);could_cot_ini(:,N) = ones(N,1);could_cot(N,N) = 0;could_cot_ini(N,N) = 0;elseidx_newc = find(ti_temp~=ti(N));zero_temp = zeros(1,N);zero_temp(idx_newc) = 1;could_cot(N,:) = zero_temp;could_cot(:,N) = zero_temp';could_cot_ini(N,:) = zero_temp;could_cot_ini(:,N) = zero_temp';endstate_temp = (1-isolate).*(1-saturation);idx_state = find(state_temp==0);could_cot(N,idx_state) = 0;could_cot(idx_state,N) = 0;could_cot_ini(N,idx_state) = 0;could_cot_ini(idx_state,N) = 0;%%%%%linklij = [lij;zeros(1,(N-1))];lij = [lij,zeros(N,1)];wij = [wij;zeros(1,(N-1))];wij = [wij,zeros(N,1)];number_couldfornew = sum(could_cot(N,:));if number_couldfornew<=m2lij(N,:) = could_cot(N,:);lij(:,N) = could_cot(:,N);wij(N,:) = 10*T*could_cot(N,:).*rand(1,N);wij(:,N) = wij(N,:)';could_cot(N,:) = zeros(N,1);could_cot(:,N) = zeros(1,N);elseK1 = (ki+1).*mi;CK1 = cumsum(K1);key_newlink = m2;while key_newlink>0KEY = rand(1,1)*CK1(N);idx_new_array = find(CK1>KEY);idx_new = idx_new_array(1);if could_cot(N,idx_new)==1lij(N,idx_new)=1;lij(idx_new,N)=1;could_cot(N,idx_new)=0;could_cot(idx_new,N)=0;wij(N,idx_new)=rand(1,1)*10*T;wij(idx_new,N)=wij(N,idx_new);key_newlink = key_newlink-1;endendend%% Refresh data%% Refresh degreeski = sum(lij)';%% Refresh resourcemi = mi.*(1+delta*(ki+1)/(sum(ki)+N));%% Get performancetempones = ones(1,N);meshmi = meshgrid(mi,tempones);meshmj = meshmi';pij = sqrt(meshmi.*meshmj).*lij;Egt(nt) = sum(sum(pij))/(N*(N-1)/2);Dgt(nt) = sum(sum((pij-Egt(nt)).^2))/(N*(N-1)/2);St(nt) = sum(ki);enddij= finddij(lij);N1 = length(find(sum(dij)>0));L = sum(sum(dij))/(N1*(N1-1));zi = zeros(N,1);for ni = 1:Nlij_temp = lij(ni,:);idx_cop = find(lij_temp==1);k_cop = length(idx_cop);if k_cop>1cop_temp = lij(idx_cop,:);cop = cop_temp(:,idx_cop);fai = sum(sum(cop))/2;zi(ni) = 2*fai/(k_cop*(k_cop-1));endendZ = (sum(zi))/N1;save(['Data3000_delta',num2str(delta),'.mat']);end第二部分程序:从第一部分程序运行得到的数据文件中提取相关信息并作图,给出演化形成网络的相关信息clear all;clc;%% %%%%%%%%%%%%%%%%%%%%%%%%%%%n0 = 20;T = 3000;NT = n0+T;T_Array = 1:T;NT_Array = 1:NT;N_delta_array = 4;Array_delta = [0.0005,0.001,0.0015,0.0025];Color_Array = ['b','g','r','c'];%% %%%%%%%%%%%%%%%%%%%%%%%%%%%StDelta = zeros(T,N_delta_array);EgtDelta = zeros(T,N_delta_array);DgtDelta = zeros(T,N_delta_array);kiDelta = zeros(NT,N_delta_array);ziDelta = zeros(NT,N_delta_array);dijDelta = zeros(NT,NT,N_delta_array);KDelta = zeros(1,N_delta_array);VDelta = zeros(1,N_delta_array);LDelta = zeros(1,N_delta_array);UDelta = zeros(1,N_delta_array);ZDelta = zeros(1,N_delta_array);%% %%%%%%%%%%%%%%%%%%%%%%%%%%%load Data3000_delta0.0005.mat;run = 1StDelta(:,1) = St;EgtDelta(:,1) = Egt;DgtDelta(:,1) = Dgt;kiDelta(:,1) = ki;ziDelta(:,1) = zi;dijDelta(:,:,1) = dij;KDelta(1) = sum(ki)/NT;VDelta(1) = sqrt((sum(ki-KDelta(1)).^2)/NT);N1 = length(find(sum(dij)>0));L = sum(sum(dij))/(N1*(N1-1));LDelta(1) = L;ZDelta(1) = (sum(zi))/N1;temp = 0;for niuij = 1:Nfor njuij = 1:Nif niuij~=njuijtemp = temp + abs(ki(niuij)-ki(njuij));endendendUDelta(1) = temp/sum(ki);%% %%%%%%%%%%%%%%%%%%%%%%%%%%%load Data3000_delta0.001.mat;run = 2StDelta(:,2) = St;EgtDelta(:,2) = Egt;DgtDelta(:,2) = Dgt;kiDelta(:,2) = ki;ziDelta(:,2) = zi;dijDelta(:,:,2) = dij;KDelta(2) = sum(ki)/NT;VDelta(2) = sqrt((sum(ki-KDelta(1)).^2)/NT);N1 = length(find(sum(dij)>0));L = sum(sum(dij))/(N1*(N1-1));LDelta(2) = L;ZDelta(2) = (sum(zi))/N1;temp = 0;for niuij = 1:Nfor njuij = 1:Nif niuij~=njuijtemp = temp + abs(ki(niuij)-ki(njuij));endendendUDelta(2) = temp/sum(ki);%% %%%%%%%%%%%%%%%%%%%%%%%%%%% load Data3000_delta0.0015.mat;run = 3StDelta(:,3) = St;EgtDelta(:,3) = Egt;DgtDelta(:,3) = Dgt;kiDelta(:,3) = ki;ziDelta(:,3) = zi;dijDelta(:,:,3) = dij;KDelta(3) = sum(ki)/NT;VDelta(3) = sqrt((sum(ki-KDelta(1)).^2)/NT);N1 = length(find(sum(dij)>0));L = sum(sum(dij))/(N1*(N1-1));LDelta(3) = L;ZDelta(3) = (sum(zi))/N1;temp = 0;for niuij = 1:Nfor njuij = 1:Nif niuij~=njuijtemp = temp + abs(ki(niuij)-ki(njuij));endendendUDelta(3) = temp/sum(ki);%% %%%%%%%%%%%%%%%%%%%%%%%%%%% load Data3000_delta0.0025.mat;run = 4StDelta(:,4) = St;EgtDelta(:,4) = Egt;DgtDelta(:,4) = Dgt;kiDelta(:,4) = ki;ziDelta(:,4) = zi;dijDelta(:,:,4) = dij;KDelta(4) = sum(ki)/NT;VDelta(4) = sqrt((sum(ki-KDelta(1)).^2)/NT);N1 = length(find(sum(dij)>0));L = sum(sum(dij))/(N1*(N1-1));LDelta(4) = L;ZDelta(4) = (sum(zi))/N1;temp = 0;for niuij = 1:Nfor njuij = 1:Nif niuij~=njuijtemp = temp + abs(ki(niuij)-ki(njuij));endendendUDelta(4) = temp/sum(ki);%% %%%%%%%%%%%%%%%%%%%%%%%%%% Array_delta = [0.0005,0.001,0.0015,0.0025];%% %%%%%%%%%%%%%%%%%%%%%%%%%% figure(1);for nf = 1:4plot(T_Array,StDelta(:,nf),Color_Array(nf));hold on;endlegend('\delta=0.0005','\delta=0.001',...'\delta=0.0015','\delta=0.0025');title('不同\delta时网络边数随运行步数变化图');hold offfigure(2);subplot(1,2,1);for nf = 1:4plot(T_Array,EgtDelta(:,nf),Color_Array(nf));hold on;endlegend('\delta=0.0005','\delta=0.001',...'\delta=0.0015','\delta=0.0025');title('不同\delta时网络效率随步数变化图');subplot(1,2,2);for nf = 1:4plot(T_Array,DgtDelta(:,nf),Color_Array(nf));hold on;endlegend('\delta=0.0005','\delta=0.001',...'\delta=0.0015','\delta=0.0025');title('不同\delta时网络效率方差随步数变化图');hold off;figure(3);subplot(1,2,1);plot(Array_delta,EgtDelta(T,:));title('期末网络效率随\delta的变化情况图');subplot(1,2,2);plot(Array_delta,DgtDelta(T,:));title('期末网络效率方差随\delta的变化情况图');hold off;figure(4);plotyy(Array_delta,LDelta,Array_delta,ZDelta);title('网络平均长度与聚集系数随\delta的变化情况图');hold off;figure(5);for nf = 1:4[numberk,karray] = hist(kiDelta(:,nf),unique(kiDelta(:,nf)));scatter(log(karray),log(numberk/N),'Marker','s','Markerfacecolor','k','markeredgecolor','k');hold on;endlegend('\delta=0.0005','\delta=0.001',...'\delta=0.0015','\delta=0.0025');title('不同\delta 时期末网络度的分布图');hold off;figure(6);subplot(1,4,1);plot(Array_delta,KDelta);hold off;subplot(1,4,2);plot(Array_delta,VDelta);hold off;subplot(1,4,3);plot(Array_delta,LDelta);hold off;subplot(1,4,4);plot(Array_delta,UDelta);hold off;第三部分程序:计算等规模随机网络的网络平均距离与网络聚集系数clear all;clc;N = 3020;NL = 222000/2;randkey = rand(N,N).*(1-tril(ones(N,N),0));reshape_randkey = reshape(randkey,N*N,1);sort_reshape_randkey = sort(reshape_randkey,'descend');idx_link = find(randkey>=sort_reshape_randkey(NL));lij = zeros(N,N);lij(idx_link) = 1;lij = lij+lij';dij = finddij(lij);L = sum(sum(dij))/(N*(N-1));zi = zeros(N,1);for ni = 1:Nlij_temp = lij(ni,:);idx_cop = find(lij_temp==1);k_cop = length(idx_cop);if k_cop>1cop_temp = lij(idx_cop,:);cop = cop_temp(:,idx_cop);fai = sum(sum(cop))/2;zi(ni) = 2*fai/(k_cop*(k_cop-1));endendZ = (sum(zi))/N;disp(['L=',num2str(L)]);disp(['Z=',num2str(Z)]);第四部分程序:第一部分程序和第三部分程序中用到的自定义函数findlij%% 该函数的输入参数为网络连接状况的矩阵lij(维度N N,其中N为网络中点的个数)%% 该函数的输出参数为点与点之间距离的矩阵dij(维度N N)%% 该函数的作用为由当前网络的连接状况(矩阵lij)计算出各点与点之间的距离(矩阵dij)function dij = finddij(lij)N = length(lij);dij = lij;for ni = 1:Nlij_temp = lij(ni,:);idx = find(lij_temp==1);Nidx = length(idx);for nix = 1:Nidxfor njx = nix+1:Nidxif dij(idx(nix),idx(njx))==0dij(idx(nix),idx(njx)) = 2;dij(idx(njx),idx(nix)) = 2;endendendendkeynd = 1;nd = 2;while keynd==1keynd = 0;for ni = 1:Ndij_temp = dij(ni,:);idx_one = find(dij_temp==1);idx_have = find(dij_temp==nd);N_one = length(idx_one);N_have = length(idx_have);if (N_one>0)&&(N_have>0)for nj = 1:N_havefor nx = 1:N_oneif dij(idx_have(nj),idx_one(nx))==0dij(idx_have(nj),idx_one(nx)) = nd+1;dij(idx_one(nx),idx_have(nj)) = nd+1;keynd = 1;endendendendendnd = nd+1;end。

matlab数值模拟代码

matlab数值模拟代码
以下是一个简单的 MATLAB 数值模拟代码示例,用于求解一维扩散方程:
matlab复制代码
% 参数设置
L = 10; % 空间域的长度
T = 1; % 时间域的长度
N = 100; % 空间域的网格数
M = 1000; % 时间域的网格数
D = 1; % 扩散系数
% 初始条件
u0 = sin(pi*x); % 初始函数
x = linspace(0,L,N); % 空间域的网格点
t = linspace(0,T,M); % 时间域的网格点
X = meshgrid(x,t); % 生成网格矩阵
U = u0(:); % 将初始函数展开成列向量
% 建立方程
A = D*[zeros(N-1,N); eye(N-1); zeros(N-1,N)]; % 系数矩阵
b = zeros(N,1); % 常数向量
f = -2*pi^2*sin(pi*X(:,1)); % 源项
% 时间循环
for k=1:M-1
u = U; % 初始化解向量
for i=2:N-1
u(i) = (A(i,i-1)*u(i-1) + A(i,i)*u(i) + A(i,i+1)*u(i+1) - f(i))/b(i); % 求解方程
end
U = u; % 将解向量保存到 U 中
end
% 可视化结果
surf(x,t,U); % 可视化结果
这个代码使用有限差分法求解一维扩散方程,其中 A 是系数矩阵,b 是常数向量,f 是源项。

在时间循环中,我们使用迭代法求解方程组,并更新解向量U。

最后,我们使用surf 函数将结果可视化。

调制解调matlab仿真源码

一、概述调制解调技术是无线通信中的重要组成部分,它能够将数字信号转换成模拟信号,通过无线信道传输,并在接收端将模拟信号转换成数字信号。

在通信系统中,调制解调技术的准确性和稳定性对整个系统的性能起着至关重要的作用。

而Matlab作为一种强大的数学计算软件,其仿真源码能够帮助工程师们更好地理解调制解调原理,优化系统设计。

二、调制解调技术概述1. 调制技术调制技术是指利用某种载波信号来传送信息信号的过程。

常见的调制技术包括幅度调制(AM)、频率调制(FM)和相位调制(PM)等。

2. 解调技术解调技术是指将调制后的信号还原成原始信号的过程。

解调技术根据调制技术的不同可以分为幅度解调、频率解调和相位解调等。

三、调制解调Matlab仿真源码1. 调制仿真源码在Matlab中,可以利用Simulink工具箱进行调制仿真源码的编写。

对于AM调制可以通过搭建AM调制系统模型,设置载波频率、调制信号频率和调制指数等参数,然后进行仿真验证调制效果。

另外,Matlab还提供了丰富的调制函数库,如ammod()函数用于进行AM调制,fmmod()函数用于进行FM调制,pmmod()函数用于进行PM调制等。

工程师们可以通过编写简单的脚本文件调用这些函数,实现调制仿真源码的编写。

2. 解调仿真源码同样地,在Matlab中可以利用Simulink工具箱进行解调仿真源码的编写。

对于AM解调可以通过搭建AM解调系统模型,设置解调信号频率和解调环节参数,然后进行仿真验证解调效果。

Matlab还提供了一系列的解调函数库,如amdemod()函数用于进行AM解调,fmdemod()函数用于进行FM解调,pmdemod()函数用于进行PM解调等。

工程师们同样可以通过编写简单的脚本文件调用这些函数,实现解调仿真源码的编写。

四、调制解调Matlab仿真实例下面我们以AM调制解调为例,展示如何使用Matlab编写调制解调仿真源码。

1. AM调制仿真源码``` matlab设置参数fc = 1000; 载波信号频率fm = 100; 调制信号频率ka = 1; 调制指数t = 0:0.001:1; 时间范围生成调制信号m_t = cos(2*pi*fm*t); 调制信号c_t = cos(2*pi*fc*t); 载波信号s_t = (1+ka*m_t).*c_t; AM调制信号绘制调制信号图像subplot(3,1,1);plot(t,m_t);title('调制信号');绘制载波信号图像subplot(3,1,2);plot(t,c_t);title('载波信号');绘制AM调制信号图像subplot(3,1,3);plot(t,s_t);title('AM调制信号');```2. AM解调仿真源码``` matlab设置解调参数fs = xxx; 采样频率t = 0:1/fs:1; 时间范围s_t = (1+ka*m_t).*c_t; AM调制信号解调信号y = amdemod(s_t,fc,fs,0,ka);t = 0:1/fs:1; 时间范围绘制解调信号图像subplot(2,1,1);plot(t,m_t);title('调制信号');绘制解调信号图像subplot(2,1,2);plot(t,y);title('解调信号');```通过上述实例,我们可以清晰地了解到如何利用Matlab编写调制解调的仿真源码,从而深入理解调制解调原理,优化系统设计。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Matlab Code for LEACH NodeNums = 100; % the num of node AreaR = 100 ; % the area of simulate NodeTranR=10; % the transit Radius Elec=50 * 10^(-9); % Eamp=100*10^(-12); Bx=50; % The Postion of Baseation By=175; MaxInteral =700; % the leach simulate time Pch=0.05; % the desired percentage of cluster heads InitEn=0.5; % the init energy of all node Tr=30; TDMA=100; Kbit=2000; % the bits of a node transmiting a packet every time BandWitch = 1*10.^(6); % Channel Bandwitch TOS_LOCAL_ADDRESS = 0; for i=1:(MaxInteral) AliveNode(i)=NodeNums; AmountData(i)=0; end sym alldata; alldata=0; LAECH = zeros(1,MaxInteral); LAENO = zeros(1,MaxInteral); for i=1:1:NodeNums EnNode(i)=InitEn; % the init energy of all node StateNode(i)=1; % the State of all node 1: alive 0:dead ClusterHeads(i)=0; % the Set of Cluster Head ,1: cluster head 0 :node

Rounds=0; % the round end Threshold=0; % the threshold of node becoming a cluster-head

Node.x=AreaR*rand(1,NodeNums); % the position of node Node.y=AreaR*rand(1,NodeNums); Node.c=zeros(1,NodeNums); Node.d=zeros(1,NodeNums); Node.l=zeros(1,NodeNums); Node.csize=zeros(1,NodeNums); Node.initclEn=zeros(1,NodeNums); % for i=1:NodeNums % Node.c(i)=0; % the Cluster head of node % Node.d(i)=0; % the distance between cluster head and node % Node.l(i)=Kbit; % the length of node i transmit packet % Node.csize(i)=0; % end

for Rounds = 1:MaxInteral % the Setup phase of cluster Node.csize=Node.csize-Node.csize; Node.d=Node.d-Node.d; Node.c=Node.c-Node.c; for i =1:NodeNums Threshold=Pch/(1-Pch*(mod(Rounds-1,1/Pch))); if StateNode(i)==1 % if node is alive if ClusterHeads(i) ==1 ClusterHeads(i)=0; elseif rand(1,1)

ClusterHeads(i)=1; Node.c(i)=TOS_LOCAL_ADDRESS; Node.initclEn(i)=EnNode(i); else ClusetHeads(i)=0; Node.initclEn(i)=EnNode(i); end end end if sum(ClusterHeads)==0 continue; end

EntranPCH = Elec * Kbit+ Eamp*Kbit*((Tr.^2+Tr.^2)); % The expended engergy by new Cluster head advertising that it is new cluster head for i=1:NodeNums if ClusterHeads(i) ==1

if EnNode(i) >= EntranPCH EnNode(i) = EnNode(i) - EntranPCH ; else StateNode(i)=0; end end end for i=1:NodeNums if StateNode(i)==1 % if node is alive if ClusterHeads(i) ~=1 % the node is not cluster head for j=1:NodeNums if ClusterHeads(j) ==1 dist = ((Node.x(i)-Node.x(j)).^2)+((Node.y(i)-Node.y(j)).^2); % the distance.^2 % if dist < (Tr.^2+Tr.^2) % blong to the transmit radius EnRecP = Elec * Kbit ; if EnNode(i) >= EnRecP % the energy reciving a boardcast packet can expend EnNode(i) = EnNode(i) - EnRecP ; else StateNode(i)=0; end if Node.d(i) ==0 % choose the cluster head Node.d(i)=dist ; Node.c(i)=j; else if Node.d(i) > dist Node.d(i)=dist ; Node.c(i)=j; end end % end end %%%%% end of choosing the cluster head ,Node.c(i) save the id of %%%%% cluster head end

if StateNode(i)==1 Node.csize(Node.c(i))= Node.csize(Node.c(i))+1; end else % the node is cluster head Node.d(i)=((Node.x(i)-Bx).^2)+((Node.y(i)-By).^2) ; Node.c(i)=TOS_LOCAL_ADDRESS; end end end

% painting the node and the cluster head % for i=1:NodeNums % if ClusterHeads(i)==1 % plot(Node.x(i),Node.y(i),'rs'); % hold on; % else plot(Node.x(i),Node.y(i),'k*'); % hold on; % end % end

% the TDMA Phase alldata=0; for i=1:NodeNums if StateNode(i)==1 if ClusterHeads(i)==1

TolLengthPacket = Kbit.*Node.csize(i); alldata=alldata+TolLengthPacket; EntranPCH = Elec * TolLengthPacket+ Eamp*TolLengthPacket*(Node.d(i)); EntranPCH.*TDMA; if EnNode(i) >= EntranPCH EnNode(i) = EnNode(i) - EntranPCH ; else StateNode(i)=0; end else EntranP = Elec * Node.l(i)+ Eamp*Node.l(i)*(Node.d(i)); EntranP=EntranP.*TDMA; if EnNode(i) >= EntranP EnNode(i) = EnNode(j)-EntranP; else StateNode(i)=0; % the node dead end EnRecP = Elec * Node.l(i) ; EnRecP=EnRecP.*TDMA; if EnNode(Node.c(i)) >= EnRecP EnNode(Node.c(i)) = EnNode(i) - EnRecP ; else StateNode(Node.c(i))=0; end end end end if Rounds==1 AmountData(Rounds)=alldata; else AmountData(Rounds)=alldata+AmountData(Rounds-1);

相关文档
最新文档