matlab源代码实例

合集下载

matlab光流法源代码

matlab光流法源代码

matlab光流法源代码以下是一个简单的MATLAB光流法源代码示例:matlab.% 读取视频文件。

videoFile = 'path_to_video_file'; % 替换为视频文件的路径。

videoObj = VideoReader(videoFile);% 读取第一帧图像。

frame1 = readFrame(videoObj);frame1_gray = rgb2gray(frame1);% 初始化光流估计器。

opticalFlow = opticalFlowLK('NoiseThreshold', 0.01); % 遍历视频的每一帧并计算光流。

while hasFrame(videoObj)。

% 读取当前帧图像。

frame2 = readFrame(videoObj);frame2_gray = rgb2gray(frame2);% 计算光流向量。

flow = estimateFlow(opticalFlow, frame1_gray); % 可视化光流向量。

imshow(frame1);hold on;plot(flow, 'DecimationFactor', [5 5], 'ScaleFactor', 10);hold off;drawnow;% 更新帧和光流向量。

frame1_gray = frame2_gray;end.请注意,这只是一个简单的光流法示例,使用了MATLAB的光流估计器函数`opticalFlowLK`。

你需要将`path_to_video_file`替换为实际的视频文件路径。

此代码将逐帧计算光流向量,并在每一帧上绘制光流向量的可视化结果。

这只是光流法的一个基本示例,实际应用中可能需要更复杂的光流估计器或其他处理步骤。

希望这个简单的代码示例能够帮助你入门光流法的实现。

割平面算法matlab源代码

割平面算法matlab源代码

割平面算法matlab源代码【原创实用版】目录1.割平面算法概述2.MATLAB 简介3.割平面算法 MATLAB 实现步骤4.割平面算法 MATLAB 源代码示例5.总结正文一、割平面算法概述割平面算法是一种在计算机图形学和几何处理领域中广泛应用的算法,主要用于求解两个或多个平面之间的交线。

在实际应用中,割平面算法可以有效地解决场景中的可视化问题,例如在计算机辅助设计(CAD)和虚拟现实(VR)等领域。

二、MATLAB 简介MATLAB(Matrix Laboratory)是一款强大的数学软件,广泛应用于科学计算、数据分析、可视化等领域。

它具有丰富的函数库和良好的图形界面,使得用户可以方便地完成各种复杂的数学运算和分析任务。

在计算机图形学和几何处理方面,MATLAB 也提供了一系列实用的工具箱,如Computer Vision Toolbox、Image Processing Toolbox 等。

三、割平面算法 MATLAB 实现步骤1.准备数据:创建两个或多个平面的参数方程,包括平面的法向量、截距等。

2.计算平面间的交线:通过求解方程组,找到两个或多个平面的交线。

3.绘制结果:使用 MATLAB 的图形函数,将计算得到的交线绘制出来,便于观察和分析。

四、割平面算法 MATLAB 源代码示例下面是一个简单的割平面算法 MATLAB 源代码示例:```matlab% 创建两个平面的参数方程plane1 = [1, 0, 0; 0, 1, 0; 0, 0, 1]; % x-y 平面plane2 = [1, 0, 0; 0, 1, 1; 0, 0, 2]; % x-y-z 平面% 计算平面间的交线交线 = [plane1(1:2, 3), plane2(1:2, 3)];% 绘制结果figure;plot3(交线 (:, 1), 交线 (:, 2), 交线 (:, 3));xlabel("x");ylabel("y");zlabel("z");title("割平面示例");```五、总结割平面算法在计算机图形学和几何处理领域具有重要意义。

matlab编程实例100例

matlab编程实例100例

1-32是:图形应用篇33-66是:界面设计篇67-84是:图形处理篇85-100是:数值分析篇实例1:三角函数曲线(1)function shili01h0=figure('toolbar','none',...'position',[198 56 350 300],...'name','实例01');h1=axes('parent',h0,...'visible','off');x=-pi:0.05:pi;y=sin(x);plot(x,y);xlabel('自变量X');ylabel('函数值Y');title('SIN( )函数曲线');grid on实例2:三角函数曲线(2)function shili02h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例02');x=-pi:0.05:pi;y=sin(x)+cos(x);plot(x,y,'-*r','linewidth',1);grid onxlabel('自变量X');ylabel('函数值Y');title('三角函数');实例3:图形的叠加function shili03h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例03');x=-pi:0.05:pi;y1=sin(x);y2=cos(x);plot(x,y1,...'-*r',...x,y2,...'--og');grid onxlabel('自变量X');ylabel('函数值Y');title('三角函数');实例4:双y轴图形的绘制function shili04h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例04');x=0:900;a=1000;b=0.005;y1=2*x;y2=cos(b*x);[haxes,hline1,hline2]=plotyy(x,y1,x,y2,'semilogy','plot'); axes(haxes(1))ylabel('semilog plot');axes(haxes(2))ylabel('linear plot');实例5:单个轴窗口显示多个图形function shili05h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例05');t=0:pi/10:2*pi;[x,y]=meshgrid(t);subplot(2,2,1)plot(sin(t),cos(t))axis equalsubplot(2,2,2)z=sin(x)-cos(y);plot(t,z)axis([0 2*pi -2 2])subplot(2,2,3)h=sin(x)+cos(y);plot(t,h)axis([0 2*pi -2 2])subplot(2,2,4)g=(sin(x).^2)-(cos(y).^2);plot(t,g)axis([0 2*pi -1 1])实例6:图形标注function shili06h0=figure('toolbar','none',...'position',[200 150 450 400],...'name','实例06');t=0:pi/10:2*pi;h=plot(t,sin(t));xlabel('t=0到2\pi','fontsize',16);ylabel('sin(t)','fontsize',16);title('\it{从0to2\pi 的正弦曲线}','fontsize',16) x=get(h,'xdata');y=get(h,'ydata');imin=find(min(y)==y);imax=find(max(y)==y);text(x(imin),y(imin),...['\leftarrow最小值=',num2str(y(imin))],...'fontsize',16)text(x(imax),y(imax),...['\leftarrow最大值=',num2str(y(imax))],...'fontsize',16)实例7:条形图形function shili07h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例07');tiao1=[562 548 224 545 41 445 745 512];tiao2=[47 48 57 58 54 52 65 48];t=0:7;bar(t,tiao1)xlabel('X轴');ylabel('TIAO1值');h1=gca;h2=axes('position',get(h1,'position'));plot(t,tiao2,'linewidth',3)set(h2,'yaxislocation','right','color','none','xticklabel',[]) 实例8:区域图形function shili08h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例08');x=91:95;profits1=[88 75 84 93 77];profits2=[51 64 54 56 68];profits3=[42 54 34 25 24];profits4=[26 38 18 15 4];area(x,profits1,'facecolor',[0.5 0.9 0.6],...'edgecolor','b',...'linewidth',3)hold onarea(x,profits2,'facecolor',[0.9 0.85 0.7],...'edgecolor','y',...'linewidth',3)hold onarea(x,profits3,'facecolor',[0.3 0.6 0.7],...'edgecolor','r',...'linewidth',3)hold onarea(x,profits4,'facecolor',[0.6 0.5 0.9],...'edgecolor','m',...'linewidth',3)hold offset(gca,'xtick',[91:95])set(gca,'layer','top')gtext('\leftarrow第一季度销量')gtext('\leftarrow第二季度销量')gtext('\leftarrow第三季度销量')gtext('\leftarrow第四季度销量')xlabel('年','fontsize',16);ylabel('销售量','fontsize',16);实例9:饼图的绘制function shili09h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例09');t=[54 21 35;68 54 35;45 25 12;48 68 45;68 54 69];x=sum(t);h=pie(x);textobjs=findobj(h,'type','text');str1=get(textobjs,{'string'});val1=get(textobjs,{'extent'});oldext=cat(1,val1{:});names={'商品一:';'商品二:';'商品三:'};str2=strcat(names,str1);set(textobjs,{'string'},str2)val2=get(textobjs,{'extent'});newext=cat(1,val2{:});offset=sign(oldext(:,1)).*(newext(:,3)-oldext(:,3))/2; pos=get(textobjs,{'position'});textpos=cat(1,pos{:});textpos(:,1)=textpos(:,1)+offset;set(textobjs,{'position'},num2cell(textpos,[3,2]))实例10:阶梯图function shili10h0=figure('toolbar','none',...'position',[200 150 450 400],...'name','实例10');a=0.01;b=0.5;t=0:10;f=exp(-a*t).*sin(b*t);stairs(t,f)hold onplot(t,f,':*')hold offglabel='函数e^{-(\alpha*t)}sin\beta*t的阶梯图'; gtext(glabel,'fontsize',16)xlabel('t=0:10','fontsize',16)axis([0 10 -1.2 1.2])实例11:枝干图function shili11h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例11');x=0:pi/20:2*pi;y1=sin(x);y2=cos(x);h1=stem(x,y1+y2);hold onh2=plot(x,y1,'^r',x,y2,'*g');hold offh3=[h1(1);h2];legend(h3,'y1+y2','y1=sin(x)','y2=cos(x)') xlabel('自变量X');ylabel('函数值Y');title('正弦函数与余弦函数的线性组合');实例12:罗盘图function shili12h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例12');winddirection=[54 24 65 84256 12 235 62125 324 34 254];windpower=[2 5 5 36 8 12 76 14 10 8];rdirection=winddirection*pi/180;[x,y]=pol2cart(rdirection,windpower); compass(x,y);desc={'风向和风力','气象台','10月1日0:00到','10月1日12:00'};gtext(desc)实例13:轮廓图function shili13h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例13');[th,r]=meshgrid((0:10:360)*pi/180,0:0.05:1); [x,y]=pol2cart(th,r);z=x+i*y;f=(z.^4-1).^(0.25);contour(x,y,abs(f),20)axis equalxlabel('实部','fontsize',16);ylabel('虚部','fontsize',16);h=polar([0 2*pi],[0 1]);delete(h)hold oncontour(x,y,abs(f),20)实例14:交互式图形function shili14h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例14');axis([0 10 0 10]);hold onx=[];y=[];n=0;disp('单击鼠标左键点取需要的点'); disp('单击鼠标右键点取最后一个点'); but=1;while but==1[xi,yi,but]=ginput(1);plot(xi,yi,'bo')n=n+1;disp('单击鼠标左键点取下一个点');x(n,1)=xi;y(n,1)=yi;endt=1:n;ts=1:0.1:n;xs=spline(t,x,ts);ys=spline(t,y,ts);plot(xs,ys,'r-');hold off实例14:交互式图形function shili14h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例14');axis([0 10 0 10]);hold onx=[];y=[];n=0;disp('单击鼠标左键点取需要的点'); disp('单击鼠标右键点取最后一个点'); but=1;while but==1[xi,yi,but]=ginput(1);plot(xi,yi,'bo')n=n+1;disp('单击鼠标左键点取下一个点');x(n,1)=xi;y(n,1)=yi;endt=1:n;ts=1:0.1:n;xs=spline(t,x,ts);ys=spline(t,y,ts);plot(xs,ys,'r-');hold off实例15:变换的傅立叶函数曲线function shili15h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例15');axis equalm=moviein(20,gcf);set(gca,'nextplot','replacechildren') h=uicontrol('style','slider','position',...[100 10 500 20],'min',1,'max',20) for j=1:20plot(fft(eye(j+16)))set(h,'value',j)m(:,j)=getframe(gcf);endclf;axes('position',[0 0 1 1]);movie(m,30)实例16:劳伦兹非线形方程的无序活动function shili15h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例15');axis equalm=moviein(20,gcf);set(gca,'nextplot','replacechildren') h=uicontrol('style','slider','position',...[100 10 500 20],'min',1,'max',20) for j=1:20plot(fft(eye(j+16)))set(h,'value',j)m(:,j)=getframe(gcf);endclf;axes('position',[0 0 1 1]);movie(m,30)实例17:填充图function shili17h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例17');t=(1:2:15)*pi/8;x=sin(t);y=cos(t);fill(x,y,'r')axis square offtext(0,0,'STOP',...'color',[1 1 1],...'fontsize',50,...'horizontalalignment','center') 例18:条形图和阶梯形图function shili18h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例18');subplot(2,2,1)x=-3:0.2:3;y=exp(-x.*x);bar(x,y)title('2-D Bar Chart')subplot(2,2,2)x=-3:0.2:3;y=exp(-x.*x);bar3(x,y,'r')title('3-D Bar Chart')subplot(2,2,3)x=-3:0.2:3;y=exp(-x.*x);stairs(x,y)title('Stair Chart')subplot(2,2,4)x=-3:0.2:3;y=exp(-x.*x);barh(x,y)title('Horizontal Bar Chart')实例19:三维曲线图function shili19h0=figure('toolbar','none',...'position',[200 150 450 400],...'name','实例19');subplot(2,1,1)x=linspace(0,2*pi);y1=sin(x);y2=cos(x);y3=sin(x)+cos(x);z1=zeros(size(x));z2=0.5*z1;z3=z1;plot3(x,y1,z1,x,y2,z2,x,y3,z3)grid onxlabel('X轴');ylabel('Y轴');zlabel('Z轴');title('Figure1:3-D Plot')subplot(2,1,2)x=linspace(0,2*pi);y1=sin(x);y2=cos(x);y3=sin(x)+cos(x);z1=zeros(size(x));z2=0.5*z1;z3=z1;plot3(x,z1,y1,x,z2,y2,x,z3,y3)grid onxlabel('X轴');ylabel('Y轴');zlabel('Z轴');title('Figure2:3-D Plot')实例20:图形的隐藏属性function shili20h0=figure('toolbar','none',...'position',[200 150 450 300],...'name','实例20');subplot(1,2,1)[x,y,z]=sphere(10);mesh(x,y,z)axis offtitle('Figure1:Opaque')hidden onsubplot(1,2,2)[x,y,z]=sphere(10);mesh(x,y,z)axis offtitle('Figure2:Transparent') hidden off实例21PEAKS函数曲线function shili21h0=figure('toolbar','none',...'position',[200 100 450 450],...'name','实例21');[x,y,z]=peaks(30);subplot(2,1,1)x=x(1,:);y=y(:,1);i=find(y>0.8&y<1.2);j=find(x>-0.6&x<0.5);z(i,j)=nan*z(i,j);surfc(x,y,z)xlabel('X轴');ylabel('Y轴');zlabel('Z轴');title('Figure1:surfc函数形成的曲面') subplot(2,1,2)x=x(1,:);y=y(:,1);i=find(y>0.8&y<1.2);j=find(x>-0.6&x<0.5);z(i,j)=nan*z(i,j);surfl(x,y,z)xlabel('X轴');ylabel('Y轴');zlabel('Z轴');title('Figure2:surfl函数形成的曲面')实例22:片状图function shili22h0=figure('toolbar','none',...'position',[200 150 550 350],...'name','实例22');subplot(1,2,1)x=rand(1,20);y=rand(1,20);z=peaks(x,y*pi);t=delaunay(x,y);trimesh(t,x,y,z)hidden offtitle('Figure1:Triangular Surface Plot'); subplot(1,2,2)x=rand(1,20);y=rand(1,20);z=peaks(x,y*pi);t=delaunay(x,y);trisurf(t,x,y,z)title('Figure1:Triangular Surface Plot'); 实例23:视角的调整function shili23h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例23');x=-5:0.5:5;[x,y]=meshgrid(x);r=sqrt(x.^2+y.^2)+eps;z=sin(r)./r;subplot(2,2,1)surf(x,y,z)xlabel('X-axis')ylabel('Y-axis')zlabel('Z-axis')title('Figure1')view(-37.5,30)subplot(2,2,2)surf(x,y,z)xlabel('X-axis')ylabel('Y-axis')zlabel('Z-axis')title('Figure2')view(-37.5+90,30)subplot(2,2,3)surf(x,y,z)xlabel('X-axis')ylabel('Y-axis')zlabel('Z-axis')title('Figure3')view(-37.5,60)subplot(2,2,4)surf(x,y,z)xlabel('X-axis')ylabel('Y-axis')zlabel('Z-axis')title('Figure4')view(180,0)实例24:向量场的绘制function shili24h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例24');subplot(2,2,1)z=peaks;ribbon(z)title('Figure1')subplot(2,2,2)[x,y,z]=peaks(15);[dx,dy]=gradient(z,0.5,0.5); contour(x,y,z,10)hold onquiver(x,y,dx,dy)hold offtitle('Figure2')subplot(2,2,3)[x,y,z]=peaks(15);[nx,ny,nz]=surfnorm(x,y,z);surf(x,y,z)hold onquiver3(x,y,z,nx,ny,nz)hold offtitle('Figure3')subplot(2,2,4)x=rand(3,5);y=rand(3,5);z=rand(3,5);c=rand(3,5);fill3(x,y,z,c)grid ontitle('Figure4')实例25:灯光定位function shili25h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例25');vert=[1 1 1;1 2 1;2 2 1;2 1 1;1 1 2;12 2;2 2 2;2 1 2];fac=[1 2 3 4;2 6 7 3;4 3 7 8;15 8 4;1 2 6 5;5 6 7 8];grid offsphere(36)h=findobj('type','surface');set(h,'facelighting','phong',...'facecolor',...'interp',...'edgecolor',[0.4 0.4 0.4],...'backfacelighting',...'lit')hold onpatch('faces',fac,'vertices',vert,...'facecolor','y');light('position',[1 3 2]);light('position',[-3 -1 3]); material shinyaxis vis3d offhold off实例26:柱状图function shili26h0=figure('toolbar','none',...'position',[200 50 450 450],...'name','实例26');subplot(2,1,1)x=[5 2 18 7 39 8 65 5 54 3 2];bar(x)xlabel('X轴');ylabel('Y轴');title('第一子图');subplot(2,1,2)y=[5 2 18 7 39 8 65 5 54 3 2];barh(y)xlabel('X轴');ylabel('Y轴');title('第二子图');实例27:设置照明方式function shili27h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例27');subplot(2,2,1)sphereshading flatcamlight leftcamlight rightlighting flatcolorbaraxis offtitle('Figure1')subplot(2,2,2)sphereshading flatcamlight leftcamlight rightlighting gouraudcolorbaraxis offtitle('Figure2')subplot(2,2,3)sphereshading interpcamlight rightcamlight leftlighting phongcolorbaraxis offtitle('Figure3')subplot(2,2,4)sphereshading flatcamlight leftcamlight rightlighting nonecolorbaraxis offtitle('Figure4')实例28:羽状图function shili28h0=figure('toolbar','none',...'position',[200 150 450 350],...'name','实例28');subplot(2,1,1)alpha=90:-10:0;r=ones(size(alpha));m=alpha*pi/180;n=r*10;[u,v]=pol2cart(m,n);feather(u,v)title('羽状图')axis([0 20 0 10])subplot(2,1,2)t=0:0.5:10;x=0.05+i;y=exp(-x*t);feather(y)title('复数矩阵的羽状图')实例29:立体透视(1)function shili29h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例29');[x,y,z]=meshgrid(-2:0.1:2,...-2:0.1:2,...-2:0.1:2);v=x.*exp(-x.^2-y.^2-z.^2);grid onfor i=-2:0.5:2;h1=surf(linspace(-2,2,20),...linspace(-2,2,20),...zeros(20)+i);rotate(h1,[1 -1 1],30)dx=get(h1,'xdata');dy=get(h1,'ydata');dz=get(h1,'zdata');delete(h1)slice(x,y,z,v,[-2 2],2,-2)hold onslice(x,y,z,v,dx,dy,dz)hold offaxis tightview(-5,10)drawnowend实例30:立体透视(2)function shili30h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例30');[x,y,z]=meshgrid(-2:0.1:2,...-2:0.1:2,...-2:0.1:2);v=x.*exp(-x.^2-y.^2-z.^2); [dx,dy,dz]=cylinder;slice(x,y,z,v,[-2 2],2,-2)for i=-2:0.2:2h=surface(dx+i,dy,dz);rotate(h,[1 0 0],90)xp=get(h,'xdata');yp=get(h,'ydata');zp=get(h,'zdata');delete(h)hold onhs=slice(x,y,z,v,xp,yp,zp);axis tightxlim([-3 3])view(-10,35)drawnowdelete(hs)hold offend实例31:表面图形function shili31h0=figure('toolbar','none',...'position',[200 150 550 250],...'name','实例31');subplot(1,2,1)x=rand(100,1)*16-8;y=rand(100,1)*16-8;r=sqrt(x.^2+y.^2)+eps;z=sin(r)./r;xlin=linspace(min(x),max(x),33); ylin=linspace(min(y),max(y),33); [X,Y]=meshgrid(xlin,ylin);Z=griddata(x,y,z,X,Y,'cubic'); mesh(X,Y,Z)axis tighthold onplot3(x,y,z,'.','Markersize',20)subplot(1,2,2)k=5;n=2^k-1;theta=pi*(-n:2:n)/n;phi=(pi/2)*(-n:2:n)'/n;X=cos(phi)*cos(theta);Y=cos(phi)*sin(theta);Z=sin(phi)*ones(size(theta));colormap([0 0 0;1 1 1])C=hadamard(2^k);surf(X,Y,Z,C)axis square实例32:沿曲线移动的小球h0=figure('toolbar','none',...'position',[198 56 408 468],...'name','实例32');h1=axes('parent',h0,...'position',[0.15 0.45 0.7 0.5],...'visible','on');t=0:pi/24:4*pi;y=sin(t);plot(t,y,'b')n=length(t);h=line('color',[0 0.5 0.5],...'linestyle','.',...'markersize',25,...'erasemode','xor');k1=uicontrol('parent',h0,...'style','pushbutton',...'position',[80 100 50 30],...'string','开始',...'callback',[...'i=1;',...'k=1;,',...'m=0;,',...'while 1,',...'if k==0,',...'break,',...'end,',...'if k~=0,',...'set(h,''xdata'',t(i),''ydata'',y(i)),',...'drawnow;,',...'i=i+1;,',...'if i>n,',...'m=m+1;,',...'i=1;,',...'end,',...'end,',...'end']);k2=uicontrol('parent',h0,...'style','pushbutton',...'position',[180 100 50 30],...'string','停止',...'callback',[...'k=0;,',...'set(e1,''string'',m),',...'p=get(h,''xdata'');,',...'q=get(h,''ydata'');,',...'set(e2,''string'',p);,',...'set(e3,''string'',q)']); k3=uicontrol('parent',h0,...'style','pushbutton',...'position',[280 100 50 30],...'string','关闭',...'callback','close');e1=uicontrol('parent',h0,...'style','edit',...'position',[60 30 60 20]);t1=uicontrol('parent',h0,...'style','text',...'string','循环次数',...'position',[60 50 60 20]);e2=uicontrol('parent',h0,...'style','edit',...'position',[180 30 50 20]); t2=uicontrol('parent',h0,...'style','text',...'string','终点的X坐标值',...'position',[155 50 100 20]); e3=uicontrol('parent',h0,...'style','edit',...'position',[300 30 50 20]); t3=uicontrol('parent',h0,...'style','text',...'string','终点的Y坐标值',...'position',[275 50 100 20]);实例33:曲线转换按钮h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例33');x=0:0.5:2*pi;y=sin(x);h=plot(x,y);grid onhuidiao=[...'if i==1,',...'i=0;,',...'y=cos(x);,',...'delete(h),',...'set(hm,''string'',''正弦函数''),',...'h=plot(x,y);,',...'grid on,',...'else if i==0,',...'i=1;,',...'y=sin(x);,',...'set(hm,''string'',''余弦函数''),',...'delete(h),',...'h=plot(x,y);,',...'grid on,',...'end,',...'end'];hm=uicontrol(gcf,'style','pushbutton',...'string','余弦函数',...'callback',huidiao);i=1;set(hm,'position',[250 20 60 20]);set(gca,'position',[0.2 0.2 0.6 0.6])title('按钮的使用')hold on实例34:栅格控制按钮h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例34');x=0:0.5:2*pi;y=sin(x);plot(x,y)huidiao1=[...'set(h_toggle2,''value'',0),',...'grid on,',...];huidiao2=[...'set(h_toggle1,''value'',0),',...'grid off,',...];h_toggle1=uicontrol(gcf,'style','togglebutton',...'string','grid on',...'value',0,...'position',[20 45 50 20],...'callback',huidiao1);h_toggle2=uicontrol(gcf,'style','togglebutton',...'string','grid off',...'value',0,...'position',[20 20 50 20],...'callback',huidiao2);set(gca,'position',[0.2 0.2 0.6 0.6])title('开关按钮的使用')实例35:编辑框的使用h0=figure('toolbar','none',...'position',[200 150 350 250],...'name','实例35');f='Please input the letter';huidiao1=[...'g=upper(f);,',...'set(h2_edit,''string'',g),',...];huidiao2=[...'g=lower(f);,',...'set(h2_edit,''string'',g),',...];h1_edit=uicontrol(gcf,'style','edit',...'position',[100 200 100 50],...'HorizontalAlignment','left',...'string','Please input the letter',...'callback','f=get(h1_edit,''string'');',...'background','w',...'max',5,...'min',1);h2_edit=uicontrol(gcf,'style','edit',...'HorizontalAlignment','left',...'position',[100 100 100 50],...'max',5,...'min',1);h1_button=uicontrol(gcf,'style','pushbutton',...'string','小写变大写',...'position',[100 45 100 20],...'callback',huidiao1);h2_button=uicontrol(gcf,'style','pushbutton',...'string','大写变小写',...'position',[100 20 100 20],...'callback',huidiao2);实例36:弹出式菜单h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例36');x=0:0.5:2*pi;y=sin(x);h=plot(x,y);grid onhm=uicontrol(gcf,'style','popupmenu',...'string',...'sin(x)|cos(x)|sin(x)+cos(x)|exp(-sin(x))',...'position',[250 20 50 20]);set(hm,'value',1)huidiao=[...'v=get(hm,''value'');,',...'switch v,',...'case 1,',...'delete(h),',...'y=sin(x);,',...'h=plot(x,y);,',...'grid on,',...'case 2,',...'delete(h),',...'y=cos(x);,',...'h=plot(x,y);,',...'grid on,',...'case 3,',...'delete(h),',...'y=sin(x)+cos(x);,',...'h=plot(x,y);,',...'grid on,',...'case 4,',...'y=exp(-sin(x));,',...'h=plot(x,y);,',...'grid on,',...'end'];set(hm,'callback',huidiao)set(gca,'position',[0.2 0.2 0.6 0.6])title('弹出式菜单的使用')实例37:滑标的使用h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例37');[x,y]=meshgrid(-8:0.5:8);r=sqrt(x.^2+y.^2)+eps;z=sin(r)./r;h0=mesh(x,y,z);h1=axes('position',...[0.2 0.2 0.5 0.5],...'visible','off');htext=uicontrol(gcf,...'units','points',...'position',[20 30 45 15],...'string','brightness',...'style','text');hslider=uicontrol(gcf,...'units','points',...'position',[10 10 300 15],...'min',-1,...'max',1,...'style','slider',...'callback',...'brighten(get(hslider,''value''))');实例38:多选菜单h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例38');[x,y]=meshgrid(-8:0.5:8);r=sqrt(x.^2+y.^2)+eps;z=sin(r)./r;h0=mesh(x,y,z);hlist=uicontrol(gcf,'style','listbox',...'string','default|spring|summer|autumn|winter',...'max',5,...'min',1,...'position',[20 20 80 100],...'callback',[...'k=get(hlist,''value'');,',...'switch k,',...'case 1,',...'colormap default,',...'case 2,',...'colormap spring,',...'case 3,',...'colormap summer,',...'case 4,',...'colormap autumn,',...'case 5,',...'colormap winter,',...'end']);实例39:菜单控制的使用h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例39');x=0:0.5:2*pi;y=cos(x);h=plot(x,y);grid onset(gcf,'toolbar','none')hm=uimenu('label','example');huidiao1=[...'set(hm_gridon,''checked'',''on''),',...'set(hm_gridoff,''checked'',''off''),',...'grid on'];huidiao2=[...'set(hm_gridoff,''checked'',''on''),',...'set(hm_gridon,''checked'',''off''),',...'grid off'];hm_gridon=uimenu(hm,'label','grid on',...'checked','on',...'callback',huidiao1);hm_gridoff=uimenu(hm,'label','grid off',...'checked','off',...'callback',huidiao2);实例40:UIMENU菜单的应用。

matlab源代码

matlab源代码

clear,clc
%三种方法进行分水岭分割
%读入图像
f=imread('T2.bmp');
figure,mesh(double(f));%显示图像,类似集水盆地
h=fspecial('prewitt');%获得纵方向的prewitt算子
fd=double(f);
g=sqrt(imfilter(fd,h,'replicate').^2+imfilter(fd,h','replicate').^2);%使用prewitt算子进行梯度运算
l=watershed(g);%分水岭运算
wr=l==0;
rm=imregionalmin(g); %计算图像的区域最小值定位,该函数仅仅是用来观察为何分水岭算法产生这么多集水盆地
im=imextendedmin(f,2);%上面仅是产生最小值点,而该函数则是得到最小值附近的区域,此处的附近是相差2的区域
fim=f;
fim(im)=175; %将im在原图上标识出,用以观察
lim=watershed(bwdist(im));%再次分水岭计算
em=lim==0;
g2=imimposemin(g,im|em);%在梯度图上标出im和em,im是集水盆地的中心,em是分水岭l2=watershed(g2); %第三次分水岭计算
f2=f;
f2(l2==0)=255; %从原图对分水岭进行观察
figure,imshow(f2);。

调用Matlab对矩阵做奇异值分解的程序源代码

调用Matlab对矩阵做奇异值分解的程序源代码

调用Matlab对矩阵做奇异值分解的程序源代码为计算针对多目标节点集的相对连通系数需要对矩阵进行奇异值分解,为此可直接调用Matlab里的对应矩阵计算模块。

从VC++调用Matlab进行计算有两种方法:一种是通过Matlab引擎直接调用Matlab,另一种是将Matlab函数编译为dll在VC中使用。

这里采用第二种方法,通过Matlab引擎调用矩阵计算功能。

其实现代码如下。

void Connectivitys::svd_Matlab(void * destMatrixP){int i,j;double * vP=NULL,* sP=NULL;mxArray *Xin,*Vout,*Sout;Engine * ep;//显式加载Matlab动态链接库,定义其中的函数HINSTANCE hInst_libeng=LoadLibrary(“libeng.dll”);HINSTANCE hInst_libmat=LoadLibrary(“libmat.dll”);HINSTANCE hInst_libmx=LoadLibrary(“libmx.dll”);typedef Engine *(*_EngOpen)(const char *startcmd);_EngOpen engOpen=(_EngOpen)GetProcAddress(hInst_libeng,“engOpen”);typedef int(*_EngClose)(Engine*ep);_EngClose engClose=(_EngClose)GetProcAddress(hInst_libeng,“engClose”);typedef mxArray *(*_EngGetArray)(Engine *ep,const char *name);_EngGetArray engGetArray=(_EngGetArray)GetProcAddress(hInst_libeng,“engGetArray”);typedef int(*_EngPutArray)(Engine *ep,const mxArray *ap);_EngPutArray engPutArray=(_EngPutArray)GetProcAddress(hInst_libeng,“engPutArray”);typedef int(*_EngEvalString)(Engine *ep,const char *string);_EngEvalString engEvalString=(_EngEvalString)GetProcAddress(hInst_libeng,“engEvalString”);typedef mxArray *(*_MxCreateDoubleMatrix)(int m,int n,mxComplexity flag);_MxCreateDoubleMatrix mxCreateDoubleMatrix=(_MxCreateDoubleMatrix)GetProcAddress(hInst_libmx,“mxCreateDoubleMatrix”);typedef void(*_MxDestroyArray)(mxArray *pa);_MxDestroyArray mxDestroyArray=(_MxDestroyArray)GetProcAddress(hInst_libmx,“mxDestroyArray”);typedef void(*_MxSetName)(mxArray*pa,const char *s);_MxSetName mxSetName=(_MxSetName)GetProcAddress(hInst_libmx,“mxSetName”);typedef double *(*_MxGetPr)(const mxArray *pa);_MxGetPr mxGetPr=(_MxGetPr)GetProcAddress(hInst_libmx,“mxGetPr”);//调用MATLAB引擎if(!(ep=engOpen(NULL))){AfxMessageBox(_T(“Can’t start MATLAB engine”));exit(-1);}//将平均偏差矩阵载入MatlabXin=mxCreateDoubleMatrix(destNodesNum,totalNodeNum,mxREAL);mxSetName(Xin,“x”);memcpy((char *)mxGetPr(Xin),(char *)destMatrixP,destNodesNum*totalNodeNum*sizeof(double));free(destMatrixP);engPutArray(ep,Xin);//对平均偏差矩阵进行SVD分解engEvalString(ep,“[u,s,v]=svd(x);”);//获取SVD分解结果Sout=engGetArray(ep,“s”);sP=mxGetPr(Sout);Vout=engGetArray(ep,“v”);vP=mxGetPr(Vout);//利用SVD分解结果进行多尺度分析//求多目标节点集相对连通系数RCCfloat totalSum=0.0,vi=0.0;for(j=0;j<destNodesNum;j++)totalSum+=*(sP+(destNodesNum+1)*j);for(i=0;i<totalNodeNum;i++){MultiNodesRCC[i]=0.0;for(j=0;j<destNodesNum;j++){vi=*(vP+totalNodeNum*j+i);if(vi<0)vi=0-vi;MultiNodesRCC[i]+=(*(sP+(destNodesNum+1)*j)/totalSum)*vi;}}//关闭MATLAB引擎,释放分配的资源engClose(ep);mxDestroyArray(Xin);mxDestroyArray(Sout);mxDestroyArray(Vout);FreeLibrary(hInst_libeng);FreeLibrary(hInst_libmat);FreeLibrary(hInst_libmx);}-全文完-。

Matlab通信系统建模与仿真例题源代码-第三章

Matlab通信系统建模与仿真例题源代码-第三章

% ch3example1A.mclear;f_p=2400; f_s=5000; R_p=3; R_s=25; % 设计要求指标[n, fn]=buttord(f_p,f_s,R_p,R_s, 's'); % 计算阶数和截止频率Wn=2*pi*fn; % 转换为角频率[b,a]=butter(n, Wn, 's'); % 计算H(s)f=0:100:10000; % 计算频率点和频率范围s=j*2*pi*f; % s=jw=j*2*pi*fH_s=polyval(b,s)./polyval(a,s); % 计算相应频率点处H(s)的值figure(1);subplot(2,1,1); plot(f, 20*log10(abs(H_s))); % 幅频特性axis([0 10000 -40 1]);xlabel('频率Hz');ylabel('幅度dB');subplot(2,1,2); plot(f, angle(H_s)); % 相频特性xlabel('频率Hz');ylabel('相角rad');figure(2); freqs(b,a); % 也可用指令freqs直接画出H(s)的频率响应曲线。

% ch3example1B.mclear;f_p=2400; f_s=5000; R_p=3; R_s=25; % 设计要求指标[n, fn]=ellipord(f_p,f_s,R_p,R_s,'s'); % 计算阶数和截止频率Wn=2*pi*fn; % 转换为角频率[b,a]=ellip(n,R_p,R_s,Wn,'s'); % 计算H(s)f=0:100:10000; % 计算频率点和频率范围s=j*2*pi*f; % s=jw=j*2*pi*fH_s=polyval(b,s)./polyval(a,s); % 计算相应频率点处H(s)的值figure(1);subplot(2,1,1); plot(f, 20*log10(abs(H_s))); % 幅频特性axis([0 10000 -40 1]);xlabel('频率Hz');ylabel('幅度dB');subplot(2,1,2); plot(f, angle(H_s)); % 相频特性xlabel('频率Hz');ylabel('相角rad');figure(2); freqs(b,a); % 也可用指令freqs直接画出H(s)的频率响应曲线。

互信息matlab源代码

互信息matlab源代码

互信息matlab源代码互信息是一种用于评估两个变量之间相关性的统计量。

它可以用于特征选择、机器学习和数据挖掘等领域。

下面是一个用MATLAB编写的计算两个随机变量之间互信息的例子。

首先,我们定义两个随机变量X和Y。

这里我们使用正态分布生成随机数据。

```matlabmu1 = 0; mu2 = 0; sigma1 = 1; sigma2 = 1; rho = 0.5;n = 1000;接下来,我们定义一个函数`calculate_entropy`来计算随机变量的熵。

熵用于衡量随机变量的不确定性。

```matlabfunction entropy = calculate_entropy(data)frequency = tabulate(data); % 统计每个值的频率probability = frequency(:,3)/100; % 计算每个值的概率probability = probability(probability ~= 0); % 剔除概率为0的值entropy = -sum(probability.*log2(probability)); % 计算熵end```接下来,我们定义另一个函数`calculate_mutual_information`来计算X和Y之间的互信息。

```matlabfunction mi = calculate_mutual_information(x, y)joint_probability = zeros(length(unique(x)), length(unique(y)));for i=1:length(x)x_idx = find(unique(x) == x(i));y_idx = find(unique(y) == y(i));joint_probability(x_idx, y_idx) = joint_probability(x_idx, y_idx) + 1;endjoint_probability = joint_probability/sum(sum(joint_probability)); % 计算联合概率分布x_probability = sum(joint_probability,2); % 计算X的概率分布y_probability = sum(joint_probability,1); % 计算Y的概率分布entropy_x = calculate_entropy(x); % 计算X的熵entropy_y = calculate_entropy(y); % 计算Y的熵mi = 0;for i=1:size(joint_probability,1)for j=1:size(joint_probability,2)if joint_probability(i,j) ~= 0mi = mi +joint_probability(i,j)*log2(joint_probability(i,j)/(x_probability(i)*y_probabi lity(j)));endendendend```最后,我们使用这两个函数计算X和Y之间的互信息。

chen系统李雅普诺夫指数的matlab源代码

chen系统李雅普诺夫指数的matlab源代码

chen系统李雅普诺夫指数的matlab源代码以下是计算 Chen 系统的李雅普诺夫指数的 Matlab 源代码。

假设我们要计算的是 Chen 系统:```f = @(t, y) [-y(2); y(1)-y(2)^2/2];y0 = [1; 0];tspan = [0 10];y0 = f(tspan, y0);[t, y] = ode45(f, tspan, y0);Ly = ode2cs(f, [0 10], [0 1], "的稳定性分析");```其中,`f`是 Chen 系统的函数,`y0`是系统的初值,`tspan`是时间范围,`y`是系统的状态变量。

`Ly`是李雅普诺夫指数,它表示系统的稳定性。

Matlab 代码的具体步骤如下:1. 定义 Chen 系统的函数`f`,并设置初值`y0`。

2. 使用`ode45`函数求解 Chen 系统的 ODE。

3. 使用`ode2cs`函数计算李雅普诺夫指数`Ly`。

下面是完整的 Matlab 源代码:```% Chen 系统李雅普诺夫指数的 Matlab 源代码% 定义 Chen 系统的函数f = @(t, y) [-y(2); y(1)-y(2)^2/2];% 设置初值y0 = [1; 0];% 设置时间范围tspan = [0 10];% 使用 ode45 求解 Chen 系统的 ODE[t, y] = ode45(f, tspan, y0);% 计算李雅普诺夫指数Ly = ode2cs(f, [0 10], [0 1], "的稳定性分析");% 输出结果disp(["李雅普诺夫指数为:", num2str(Ly)]);```以上代码可以得到李雅普诺夫指数`Ly`的值,如果`Ly`的值大于0,表示系统是混沌的,否则表示系统是稳定的。

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

1.硬币模拟试验
源代码:
clear;
clc;
head_count=0;
p1_hist= [0];
p2_hist= [0];
n = 1000;
p1 = 0.3;
p2=0.03;
head = figure(1);
rand('seed',sum(100*clock));
for i = 1:n
tmp = rand(1);
if(tmp <= p1)
head_count = head_count + 1;
end
p1_hist (i) = head_count /i;
end
figure(head);
subplot(2,1,1);
plot(p1_hist);
grid on;
hold on;
xlabel('重复试验次数');
ylabel('正面向上的比率');
title('p=0.3试验次数N与正面向上比率的函数图');
head_count=0;
for i = 1:n
tmp = rand(1);
if(tmp <= p2)
head_count = head_count + 1;
end
p2_hist (i) = head_count /i;
end
figure(head);
subplot(2,1,2);
plot(p2_hist);
grid on;
hold on;
xlabel('重复试验次数');
ylabel('正面向上的比率');
title('p=0.03试验次数N与正面向上比率的函数图');
实验结果:
2.不同次数的随机试验均值方差比较
源代码:
clear ;
clc;
close;
rand('seed',sum(100*clock));
Titles = ['n=5时'
'n=20时'
'n=25时'
'n=50时'
'n=100时'];
Titlestr = cellstr(Titles);
X_n_bar=[0]; %the samples of the X_n_bar
X_n=[0]; %the samples of X_n
N=[5,10,25,50,100];
j=1;
num_X_n = 100;
num_X_n_bar = 100;
h_X_n_bar = figure(1);
for n = 1: num_X_n
for i= 1 : num_X_n_bar
X_n = rand(1,n);
X_n_bar(i) = mean(X_n); %X_n 是我们模拟的对象end
mean_X_n_bar(n) = mean(X_n_bar); %均值
var_X_n_bar(n) = var(X_n_bar);%方差
if(n==5||n==10||n==25||n==50||n==100)
figure(h_X_n_bar)
subplot(2,2,j);
plot(X_n_bar);
grid on;
hold on;
xlabel('重复试验次数');
ylabel('Xn_bar');
axis([0 100 0 1]);
title(Titlestr(j));
j=j+1;
end
end
theory_mean_X_n_bar = [num_X_n];
theory_var_X_n_bar = [num_X_n];
for n=1:100
theory_mean_X_n_bar(n) = 0.5;
theory_var_X_n_bar(n) = 1/(12*n);
end
figure;
subplot(2,1,1);
plot(theory_mean_X_n_bar, '-r');
grid on;
hold on;
plot(mean_X_n_bar,'bo-');
xlabel('n');
ylabel('样本均值的均值');
legend('theory value','sampled value');
subplot(2,1,2);
plot(theory_var_X_n_bar, '-r');
grid on;
hold on;
plot(var_X_n_bar,'bo-');
xlabel('n');
ylabel('样本均值的方差');
legend('theory value','sampled value');实验结果:。

相关文档
最新文档