实用matlab代码
matlab经典代码大全
哈哈哈MATLAB显示正炫余炫图:plot(x,y1,'* r',x,y2,'o b')定义【0,2π】;t=0:pi/10:2*pi;定义函数文件:function [返回变量列表]=函数名(输入变量列表)顺序结构:选择结构1)if-else-end语句其格式为:if 逻辑表达式程序模块1;else程序模块2;End图片读取:%选择图片路径[filename, pathname] = ...uigetfile({'*.jpg';'*.bmp';'*.gif'},'选择图片');%合成路径+文件名str=[pathname,filename];%为什么pathname和filename要前面出现的位置相反才能运行呢???%读取图片im=imread(str);%使用图片axes(handles.axes1);%显示图片imshow(im);边缘检测:global imstr=get(hObject,'string');axes (handles.axes1);switch strcase ' 原图'imshow(im);case 'sobel'BW = edge(rgb2gray(im),'sobel');imshow(BW);case 'prewitt'BW = edge(rgb2gray(im),'prewitt');imshow(BW);case 'canny'BW = edge(rgb2gray(im),'canny');imshow(BW);Canny算子边缘定位精确性和抗噪声能力效果较好,是一个折中方案end;开闭运算:se=[1,1,1;1,1,1;1,1,1;1,1,1]; %Structuring ElementI=rgb2gray(im);imshow(I,[]);title('Original Image');I=double(I);[im_height,im_width]=size(I);[se_height,se_width]=size(se);halfheight=floor(se_height/2);halfwidth=floor(se_width/2);[se_origin]=floor((size(se)+1)/2);image_dilation=padarray(I,se_origin,0,'both'); %Image to be used for dilationimage_erosion=padarray(I,se_origin,256,'both'); %Image to be used for erosion %%%%%%%%%%%%%%%%%%%%% Dilation %%%%%%%%%%%%%%%%%%%%%for k=se_origin(1)+1:im_height+se_origin(1)for kk=se_origin(2)+1:im_width+se_origin(2)dilated_image(k-se_origin(1),kk-se_origin(2))=max(max(se+image_dilation(k-se_origin(1):k+halfh eight-1,kk-se_origin(2):kk+halfwidth-1)));endendfigure;imshow(dilated_image,[]);title('Image after Dilation'); %%%%%%%%%%%%%%%%%%%% Erosion %%%%%%%%%%%%%%%%%%%%se=se';for k=se_origin(2)+1:im_height+se_origin(2)for kk=se_origin(1)+1:im_width+se_origin(1)eroded_image(k-se_origin(2),kk-se_origin(1))=min(min(image_erosion(k-se_origin(2):k+halfwidth -1,kk-se_origin(1):kk+halfheight-1)-se));endendfigure;imshow(eroded_image,[]);title('Image after Erosion'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Opening(Erosion first, then Dilation) %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%se=se';image_dilation2=eroded_image; %Image to be used for dilationfor k=se_origin(1)+1:im_height-se_origin(1)for kk=se_origin(2)+1:im_width-se_origin(2)opening_image(k-se_origin(1),kk-se_origin(2))=max(max(se+image_dilation2(k-se_origin(1):k+hal fheight-1,kk-se_origin(2):kk+halfwidth-1)));endendfigure;imshow(opening_image,[]);title('Opening Image'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Closing(Dilation first, then Erosion) %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%se=se';image_erosion2=dilated_image; %Image to be used for erosionfor k=se_origin(2)+1:im_height-se_origin(2)for kk=se_origin(1)+1:im_width-se_origin(1)closing_image(k-se_origin(2),kk-se_origin(1))=min(min(image_erosion2(k-se_origin(2):k+halfwidt h-1,kk-se_origin(1):kk+halfheight-1)-se));endendfigure;imshow(closing_image,[]);title('Closing Image');Warning: Image is too big to fit on screen; displaying at 31% scale.> In truesize>Resize1 at 308In truesize at 44In imshow at 161图像的直方图归一化:I=imread(‘red.bmp’);%读入图像figure;%打开新窗口[M,N]=size(I);%计算图像大小[counts,x]=imhist(I,32);%计算有32个小区间的灰度直方图counts=counts/M/N;%计算归一化灰度直方图各区间的值stem(x,counts);%绘制归一化直方图图像平移:I=imread('shuichi.jpg');se=translate(strel(1),[180 190]);B=imdilate(I,se);figure;subplot(1,2,1),subimage(I);title('原图像');subplot(1,2,2),subimage(B);title('平移后图像');图像的转置;A=imread('nir.bmp');tform=maketform('affine',[0 1 0;1 0 0;0 0 1]);B=imtransform(A,tform,'nearest');figure;imshow(A);figure;imshow(B);imwrite(B,'nir转置后图像.bmp');图像滤波:B = imfilter(A,H,option1,option2,...)或写作g = imfilter(f, w, filtering_mode, boundary_options, size_options)其中,f为输入图像,w为滤波掩模,g为滤波后图像。
30个智能算法matlab代码
30个智能算法matlab代码以下是30个使用MATLAB编写的智能算法的示例代码: 1. 线性回归算法:matlab.x = [1, 2, 3, 4, 5];y = [2, 4, 6, 8, 10];coefficients = polyfit(x, y, 1);predicted_y = polyval(coefficients, x);2. 逻辑回归算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];model = fitglm(x, y, 'Distribution', 'binomial'); predicted_y = predict(model, x);3. 支持向量机算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [1, 1, -1, -1, -1];model = fitcsvm(x', y');predicted_y = predict(model, x');4. 决策树算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitctree(x', y');predicted_y = predict(model, x');5. 随机森林算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = TreeBagger(50, x', y');predicted_y = predict(model, x');6. K均值聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];idx = kmeans(data, 2);7. DBSCAN聚类算法:matlab.x = [1, 2, 3, 10, 11, 12]; y = [1, 2, 3, 10, 11, 12]; data = [x', y'];epsilon = 2;minPts = 2;[idx, corePoints] = dbscan(data, epsilon, minPts);8. 神经网络算法:matlab.x = [1, 2, 3, 4, 5];y = [0, 0, 1, 1, 1];net = feedforwardnet(10);net = train(net, x', y');predicted_y = net(x');9. 遗传算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = gaoptimset('PlotFcns', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);10. 粒子群优化算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;options = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = particleswarm(fitnessFunction, nvars, lb, ub, options);11. 蚁群算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = antColonyOptimization(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);12. 粒子群-蚁群混合算法:matlab.distanceMatrix = [0, 2, 3; 2, 0, 4; 3, 4, 0];pheromoneMatrix = ones(3, 3);alpha = 1;beta = 1;iterations = 10;bestPath = particleAntHybrid(distanceMatrix, pheromoneMatrix, alpha, beta, iterations);13. 遗传算法-粒子群混合算法:matlab.fitnessFunction = @(x) x^2 4x + 4;nvars = 1;lb = 0;ub = 5;gaOptions = gaoptimset('PlotFcns', @gaplotbestf);psOptions = optimoptions('particleswarm', 'PlotFcn',@pswplotbestf);[x, fval] = gaParticleHybrid(fitnessFunction, nvars, lb, ub, gaOptions, psOptions);14. K近邻算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcknn(x', y');predicted_y = predict(model, x');15. 朴素贝叶斯算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; y = [0, 0, 1, 1, 1];model = fitcnb(x', y');predicted_y = predict(model, x');16. AdaBoost算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3];y = [0, 0, 1, 1, 1];model = fitensemble(x', y', 'AdaBoostM1', 100, 'Tree'); predicted_y = predict(model, x');17. 高斯混合模型算法:matlab.x = [1, 2, 3, 4, 5]';y = [0, 0, 1, 1, 1]';data = [x, y];model = fitgmdist(data, 2);idx = cluster(model, data);18. 主成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = pca(x');transformed_x = x' coefficients;19. 独立成分分析算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; coefficients = fastica(x');transformed_x = x' coefficients;20. 模糊C均值聚类算法:matlab.x = [1, 2, 3, 4, 5; 1, 2, 2, 3, 3]; options = [2, 100, 1e-5, 0];[centers, U] = fcm(x', 2, options);21. 遗传规划算法:matlab.fitnessFunction = @(x) x^2 4x + 4; nvars = 1;lb = 0;ub = 5;options = optimoptions('ga', 'PlotFcn', @gaplotbestf);[x, fval] = ga(fitnessFunction, nvars, [], [], [], [], lb, ub, [], options);22. 线性规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];lb = [0; 0];ub = [];[x, fval] = linprog(f, A, b, [], [], lb, ub);23. 整数规划算法:matlab.f = [-5; -4];A = [1, 2; 3, 1];b = [8; 6];intcon = [1, 2];[x, fval] = intlinprog(f, intcon, A, b);24. 图像分割算法:matlab.image = imread('image.jpg');grayImage = rgb2gray(image);binaryImage = imbinarize(grayImage);segmented = medfilt2(binaryImage);25. 文本分类算法:matlab.documents = ["This is a document.", "Another document.", "Yet another document."];labels = categorical(["Class 1", "Class 2", "Class 1"]);model = trainTextClassifier(documents, labels);newDocuments = ["A new document.", "Another new document."];predictedLabels = classifyText(model, newDocuments);26. 图像识别算法:matlab.image = imread('image.jpg');features = extractFeatures(image);model = trainImageClassifier(features, labels);newImage = imread('new_image.jpg');newFeatures = extractFeatures(newImage);predictedLabel = classifyImage(model, newFeatures);27. 时间序列预测算法:matlab.data = [1, 2, 3, 4, 5];model = arima(2, 1, 1);model = estimate(model, data);forecastedData = forecast(model, 5);28. 关联规则挖掘算法:matlab.data = readtable('data.csv');rules = associationRules(data, 'Support', 0.1);29. 增强学习算法:matlab.environment = rlPredefinedEnv('Pendulum');agent = rlDDPGAgent(environment);train(agent);30. 马尔可夫决策过程算法:matlab.states = [1, 2, 3];actions = [1, 2];transitionMatrix = [0.8, 0.1, 0.1; 0.2, 0.6, 0.2; 0.3, 0.3, 0.4];rewardMatrix = [1, 0, -1; -1, 1, 0; 0, -1, 1];policy = mdpPolicyIteration(transitionMatrix, rewardMatrix);以上是30个使用MATLAB编写的智能算法的示例代码,每个算法都可以根据具体的问题和数据进行相应的调整和优化。
matlab有趣的代码
matlab有趣的代码Matlab是一种用于科学计算和数据可视化的强大工具。
它不仅可以解决数学问题,还可以进行图像处理、信号处理、机器学习等等。
在这篇文章中,我将为大家介绍一些有趣的Matlab代码,并解释它们的功能和应用。
1. "音乐可视化" - 利用Matlab可以将音频信号转换为可视化效果。
你可以使用Matlab的音频处理库来读取音频文件,并将其转换为时域或频域信号。
然后,你可以使用Matlab的绘图功能将这些信号可视化成波形图或频谱图。
2. "图像滤镜效果" - Matlab提供了丰富的图像处理工具箱,可以实现各种有趣的图像滤镜效果。
比如,你可以使用Matlab的边缘检测算法来突出图像的边缘特征,或者使用模糊滤镜来模糊图像。
这些滤镜效果可以使图像更加有趣和艺术化。
3. "模拟物理实验" - Matlab可以用来模拟各种物理实验,比如弹簧振子、摆钟等。
你可以使用Matlab的数值计算功能来解决物理方程,并使用Matlab的绘图功能将模拟结果可视化。
这样,你就可以通过代码实现自己的物理实验,并观察其行为和变化。
4. "游戏开发" - Matlab不仅可以用于科学计算和数据处理,还可以用于游戏开发。
你可以使用Matlab的图形库来创建简单的游戏界面,并使用Matlab的控制语句和逻辑运算来实现游戏的逻辑。
这样,你就可以通过编写Matlab代码来开发自己的小游戏。
5. "数据可视化" - Matlab提供了丰富的绘图和可视化工具,可以帮助你更好地理解和展示数据。
你可以使用Matlab的绘图函数来绘制各种统计图表,比如柱状图、折线图、散点图等。
这些图表可以帮助你更直观地理解数据的分布和趋势。
6. "机器学习应用" - Matlab提供了强大的机器学习工具箱,可以帮助你构建和训练机器学习模型。
matlab新手代码
matlab新手代码MATLAB是一种功能强大的数学软件,广泛应用于工程、科学、计算机科学和金融等领域。
MATLAB的主要优势是其简单易用的界面和强大的数学计算功能。
对于许多新手来说,MATLAB可能看起来有点令人生畏,但是一旦掌握了基础知识和编程技巧,您就能够发挥MATLAB的真正潜力。
下面是一些适用于MATLAB新手的代码技巧和指南。
索引和切片MATLAB允许您通过索引或切片获取数组的子集。
索引是指获取数组中的单个值,切片是指获取一系列值。
要索引一个数组,请使用以下语法:x = [1, 2, 3, 4, 5]; y = x(2);这将返回数组中第二个元素即2。
要进行切片,请使用以下语法:x = [1, 2, 3, 4, 5]; y = x(2:4);这将返回数组中第二个到第四个元素即[2, 3, 4]。
变量和运算操作MATLAB 支持多种类型的变量- 根据需要自动进行数据类型转换。
例如,您可以将一个字符串转换为数字或将数字转换为字符串。
以下是一些示例:x = '5'; y = str2double(x);此代码将字符串“5”转换为数字5。
您也可以将数字转换为字符串:x = 5; y = num2str(x);此代码将数字5转换为字符串“5”。
另一个常见的操作是从数组中选择最大值或最小值:x = [1, 2, 3, 4, 5]; y = max(x);这将返回数组中的最大值,即5。
要获取数组中的最小值,请使用min命令:x = [1, 2, 3, 4, 5]; y = min(x);这将返回数组中的最小值,即1。
函数和操作符MATLAB提供了许多内置函数和操作符,可用于执行各种数学运算和操作。
以下是一些示例:- 常用数学函数:x = 3; y = sqrt(x);这将分配变量y的值为变量x的平方根,即√3。
- 条件语句:x = 2; if x > 1 y = 'x is greater than 1'; else y = 'x is less than or equal to 1'; end如果变量x大于1,则分配字符串值“x is greater than 1”给变量 y,否则分配字符串“x is less than or equal to 1”给变量y。
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实验代码
二. 1.clear allm=[-5.0,-3.0,1.0,2.0,2.5,3.0,5.0];for x=mif x<0&x~=-3y1=x^2+x-6;disp(['y= ',num2str(y1)])elseif x>=0&x<5&x~=2&x~=3y2=x^2-5*x+6;disp(['y= ',num2str(y2)])elsey3=x^2-x-1;disp(['y= ',num2str(y3)])endend2.clear allx=input('请输入成绩:');while (x>100|x<0)x=input('输入错误,输入错误请重新输入成绩'); endswitch fix(x/10)case {9,10}disp('A')case {8}disp('B')case {7}disp('C')case {6}disp('D')case {0,1,2,3,4,5}disp('E')end3. clear allx=input('请输入工号:');y=input('请输入工作时长:');if y>120a=84*120+(y-120)*84*0.15;disp(['您本月基本工资是: ',num2str(a)]) elseif y<60b=84*y-700;disp(['您本月基本工资是: ',num2str(b)]) elsec=84*y;disp(['您本月基本工资是:',num2str(c)])4. clear alla=fix(rand(1)*89)+10;disp(['a=',num2str(a)])b=fix(rand(1)*89)+10;disp(['b=',num2str(b)])x=input('输入一个四则运算符号:','s');if abs(x)==43c=a+b;elseif abs(x)==45c=a-b;elseif abs(x)==42c=a*b;elseif abs(x)==47c=a/b;enddisp(['计算结果是:',num2str(c)])5. clear alla=fix(rand(5,6)*89)+10;n=input('输入一个数(输出是一个5*6的矩阵该行元素):');if n>5|n<0b=a(5:5,:);disp(['输入错误,程序输出最后一行的元素: ',num2str(b)]) elsec=a(n:n,:);disp(['输出结果是:',num2str(c)])end实验四二.1. clear alls1=0;for n=1:100x=1/(n^2);s1=s1+x;enddisp(['当N=100时:',num2str(s1)])s2=0;for n=1:1000x=1/(n^2);s2=s2+x;enddisp(['当N=1000时: ',num2str(s2)])s3=0;for n=1:10000x=1/(n^2);s3=s3+x;disp(['当N=10000时:',num2str(s3)])2. clear alln=1;y=0;while (y<3)x=1/(2*n-1);n=1+n;y=y+x;enddisp(['y<3时n的最大值是:',num2str(n-2)]) disp(['相应的y值是: ',num2str(y-x)])3. clear allx=input('请输入x的初始值:');a=input('请输入常数a的值:');b=input('请输入常数b的值:');g=a/(b+x);n=0;while ((abs(x-g))>10^-5)g=a/(b+x);x=a/(b+g);n=n+1;if n>499breakendenddisp(['迭代结果是:',num2str(x)])disp(['循环次数:',num2str(n),'´Î'])r1=(-b+sqrt(b^2+4*a))/2;r2=(-b-sqrt(b^2+4*a))/2;disp(['如果迭代收敛,准确值:',num2str(r2)]) 4. clear allfor n=1:4if n==1f1=1;elseif n==2f2=0;elseif n==3f3=1;elsea=f3-2*f2+f1;b=a-2*f3+f2;c=b-2*a+f3;d=c-2*b+a;H=[1,0,1,a,b,c,d];for m=8:4:99a=d-2*c+b;b=a-2*d+c;c=b-2*a+d;d=c-2*b+a;H=[H,a,b,c,d];endf100=d-2*c+b;endendmax=max(H);min=min(H);sum=sum(H);disp(['最大值是:',num2str(max)]) disp(['最小值是:',num2str(min)]) disp(['各数和是:',num2str(sum)]) k=0;l=0;p=0;for e=Hif e>0k=k+1;elseif e<0l=l+1;elsep=p+1;endenddisp(['正数的个数是:',num2str(k)]) disp(['负数的个数是:',num2str(l)]) disp(['零的个数是: ',num2str(p)]) 5. clear allp=0;l=0;H=[];for m=2:49a=m;b=m+1;c=a*b-1;for k=1:cif rem(c,k)==0l=l+1;endendif l==2disp(['亲密数对是','(',num2str(a),' ,',num2str(b),')']) p=p+1;H=[H,c];endl=0;endsum=sum(H);disp(['亲密数对的个数是:',num2str(p)])disp(['亲密数对的和是: ',num2str(sum)])实验五 1.clear alla=input('请输入一个复数:');[e,l,s,c]=fushu(a);函数文件名:fushu.mfunction [e,l,s,c]=fushu(x)e=exp(x);l=log(x);s=sin(x);c=cos(x);disp(['复数e的指数是:',num2str(e)])disp(['复数e的对数是:',num2str(l)])disp(['复数e的正弦是:',num2str(s)])disp(['复数e的余弦是:',num2str(c)])2. clear allm1=input('请输入m1的值:');m2=input('请输入m2的值:');m3=input('请输入θ的值:');J=jiefangcheng(m1,m2,m3);函数文件名:jiefangcheng.mfunction J=jiefangcheng(m1,m2,m3)H=[m1*cos(m3*pi/180) -m1 -sin(m3*pi/180) 0m1*sin(m3*pi/180) 0 cos(m3*pi/180) 00 m2 -sin(m3*pi/180) 00 0 -cos(m3*pi/180) 1];K=[0;m1*9.8;0;m2*9.8];J=inv(H)*K;disp(['方程组的解是:',num2str(J')])3. clear allfor n=10:99a=sushu(n);end函数文件名:sushu.mfunction a=sushu(b)x=fix(b/10);y=rem(b,10);c=0;d=0;for m=1:bif rem(b,m)==0c=c+1;endendfor n=1:10*y+xif rem((10*y+x),n)==0d=d+1;endendif c==2&d==2a=b;disp(['绝对素数是:',num2str(a)])elsea=0; %这里可以赋值,目的是请程序执行end4. clear ally=input('请输入一个数或矩阵:');disp('输入的数或矩阵x是:')disp(y)L=fx(y);函数文件名:fx.mfunction L=fx(y)[m,n]=size(y); K=[];for a=1:nfor b=1:mx=sub2ind(size(y),b,a);h=1/((x-2)^2+0.1)+1/((x-3)^4+0.01); K=[K,h];endendL=reshape(K,n,m);disp('则f(x)=')disp(L')5. clear allfor n=20:10:40if n==20;[f1,f2]=f(n);a=f1;b=f2;elseif n==30;[f1,f2]=f(n);c=f1;d=f2;else[f1,f2]=f(n);e=f1;f=f2;endendy1=e/(a+c);y2=f/(b+d);disp(['(1) y=',num2str(y1)]) disp(['(2) y=',num2str(y2)])函数文件名:f.mfunction [f1,f2]=f(n)f1=n+10*log(n^2+5);x=0;for a=1:nb=a*(a+1);x=x+b;endf2=x;实验八章1.clear all;n=0;A=rand(1,30000);meanA=mean(A);stdA=std(A,1,2);maxA=max(A);minA=min(A);for x=Aif x>0.5n=n+1;else continue;endendp=n/30000;disp(['均值=' ,num2str(meanA)]); disp(['标准差=',num2str(stdA)]);disp(['最大值max=',num2str(maxA)]); disp(['最小值min=',num2str(minA)]); disp([ '百分比P=',num2str(p)]);。
实用matlab代码
实⽤matlab代码1.图像反转MATLAB程序实现如下:I=imread('xian.bmp');J=double(I);J=-J+(256-1); %图像反转线性变换H=uint8(J);subplot(1,2,1),imshow(I);subplot(1,2,2),imshow(H);2.灰度线性变换MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);axis on; %显⽰坐标系I1=rgb2gray(I);subplot(2,2,2),imshow(I1);title('灰度图像');axis([50,250,50,200]);axis on; %显⽰坐标系J=imadjust(I1,[0.1 0.5],[]); %局部拉伸,把[0.1 0.5]内的灰度拉伸为[0 1] subplot(2,2,3),imshow(J); title('线性变换图像[0.1 0.5]');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系K=imadjust(I1,[0.3 0.7],[]); %局部拉伸,把[0.3 0.7]内的灰度拉伸为[0 1] subplot(2,2,4),imshow(K); title('线性变换图像[0.3 0.7]');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系3.⾮线性变换MATLAB程序实现如下:I=imread('xian.bmp');I1=rgb2gray(I);subplot(1,2,1),imshow(I1);title('灰度图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系J=double(I1);J=40*(log(J+1));H=uint8(J);subplot(1,2,2),imshow(H);title('对数变换图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系4.直⽅图均衡化MATLAB程序实现如下:I=imread('xian.bmp');I=rgb2gray(I);figure;subplot(2,2,1);imshow(I);subplot(2,2,2);imhist(I);I1=histeq(I);figure;subplot(2,2,1);imshow(I1);subplot(2,2,2);imhist(I1);5.线性平滑滤波器⽤MATLAB实现领域平均法抑制噪声程序:I=imread('xian.bmp');subplot(231)imshow(I)title('原始图像')I=rgb2gray(I);I1=imnoise(I,'salt & pepper',0.02);subplot(232)imshow(I1)title('添加椒盐噪声的图像')k1=filter2(fspecial('average',3),I1)/255; %进⾏3*3模板平滑滤波k2=filter2(fspecial('average',5),I1)/255; %进⾏5*5模板平滑滤波k3=filter2(fspecial('average',7),I1)/255; %进⾏7*7模板平滑滤波k4=filter2(fspecial('average',9),I1)/255; %进⾏9*9模板平滑滤波subplot(233),imshow(k1);title('3*3模板平滑滤波');subplot(234),imshow(k2);title('5*5模板平滑滤波');subplot(235),imshow(k3);title('7*7模板平滑滤波');subplot(236),imshow(k4);title('9*9模板平滑滤波');6.中值滤波器⽤MATLAB实现中值滤波程序如下:I=imread('xian.bmp');I=rgb2gray(I);J=imnoise(I,'salt&pepper',0.02);subplot(231),imshow(I);title('原图像');subplot(232),imshow(J);title('添加椒盐噪声图像');k1=medfilt2(J); %进⾏3*3模板中值滤波k2=medfilt2(J,[5,5]); %进⾏5*5模板中值滤波k3=medfilt2(J,[7,7]); %进⾏7*7模板中值滤波k4=medfilt2(J,[9,9]); %进⾏9*9模板中值滤波subplot(233),imshow(k1);title('3*3模板中值滤波'); subplot(234),imshow(k2);title('5*5模板中值滤波');subplot(235),imshow(k3);title('7*7模板中值滤波');subplot(236),imshow(k4);title('9*9模板中值滤波');7.⽤Sobel算⼦和拉普拉斯对图像锐化:I=imread('xian.bmp');subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系I1=im2bw(I);subplot(2,2,2),imshow(I1);title('⼆值图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系H=fspecial('sobel'); %选择sobel算⼦J=filter2(H,I1); %卷积运算subplot(2,2,3),imshow(J);title('sobel算⼦锐化图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系h=[0 1 0,1 -4 1,0 1 0]; %拉普拉斯算⼦J1=conv2(I1,h,'same'); %卷积运算subplot(2,2,4),imshow(J1); title('拉普拉斯算⼦锐化图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系8.梯度算⼦检测边缘⽤MATLAB实现如下:I=imread('xian.bmp');subplot(2,3,1);imshow(I);title('原始图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系I1=im2bw(I); subplot(2,3,2);imshow(I1);title('⼆值图像');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系I2=edge(I1,'roberts'); figure;subplot(2,3,3);imshow(I2);title('roberts算⼦分割结果');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系I3=edge(I1,'sobel'); subplot(2,3,4);imshow(I3);title('sobel算⼦分割结果');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系I4=edge(I1,'Prewitt'); subplot(2,3,5);imshow(I4);title('Prewitt算⼦分割结果');axis([50,250,50,200]);grid on; %显⽰⽹格线axis on; %显⽰坐标系9.LOG算⼦检测边缘⽤MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1);imshow(I);。
matlab 变量、矩阵基本运算代码
matlab 变量、矩阵基本运算代码详解
MATLAB是一种高效的编程语言和环境,主要用于数值计算和数据分析。
它支持多种数据类型,其中矩阵是最基本的数据结构之一。
下面是一些关于MATLAB变量和矩阵基本运算的代码示例。
1.变量定义
在MATLAB中,变量不需要提前声明,可以直接赋值。
例如:
2.矩阵基本运算
MATLAB支持多种矩阵基本运算,包括加法、减法、乘法和转置等。
例如:
注意,在MATLAB中,矩阵乘法需要用*符号表示,而不是普通的乘号x。
此外,MATLAB还支持一些特殊的矩阵运算,例如逆矩阵、行列式和特征值等。
例如:
3.变量替换和循环结构
MATLAB还支持变量替换和循环结构,可以方便地进行批量计算和数据处理。
例如:
以上是一些关于MATLAB变量和矩阵基本运算的代码示例,希望能对您有所帮助。
matlab编程实例100例(精编文档).doc
【最新整理,下载后即可编辑】1-32是:图形应用篇33-66是:界面设计篇67-84是:图形处理篇85-100是:数值分析篇实例1:三角函数曲线(1)function shili01h0=figure('toolbar','none',...'position',[198****0300],...'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 phongaxis 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;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****8468],...'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],...'background','w',...'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,',...'delete(h),',...'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菜单的应用h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例40');h1=uimenu(gcf,'label','函数');h11=uimenu(h1,'label','轮廓图',...'callback',[...'set(h31,''checked'',''on''),',...'set(h32,''checked'',''off''),',...'[x,y,z]=peaks;,',...'contour3(x,y,z,30)']);h12=uimenu(h1,'label','高斯分布',...'callback',[...'set(h31,''checked'',''on''),',...'set(h32,''checked'',''off''),',...'mesh(peaks);,',...'axis tight']);。
MATLAB-实验代码
实验 11、ones 语句:Y = ones(n) %生成n×n 全1 阵Y = ones(m,n) %生成m×n 全1 阵Y = ones([m n]) %生成m×n 全1 阵Y = ones(d1,d2,d3…) %生成d1×d2×d3×…全1 阵或数组Y = ones([d1 d2 d3…]) %生成d1×d2×d3×…全1 阵或数组Y = ones(size(A)) %生成与矩阵A 相同大小的全1 阵2、find 语句:k = find(x) %按行检索X 中非零元素的点,若没有非零元素,将返回空矩阵。
[i,j] = find(X) %检索X 中非零元素的行标i 和列标j 。
[i,j,v] = find(X) %检索X 中非零元素的行标i 和列标j 以及对应的元素值v 。
实验 31、编写一M 函数,a 和x 作为函数参数输入,函数里面分别用if 结构实现函数表示1()1x a x f x a x a ax a-≤-⎧⎪⎪=-<<⎨⎪≥⎪⎩function output=function1(x,a)result=0;if x<=-aresult=-1;elseif x>-a&x<aresult=x/a;else x>=aresult=1;endoutput=[result]; 2、编写一M 函数,迭代计算132n n x x +=+,给出可能的收敛值,其中x 的初值作为函数的参数输入。
function output=function2(x)y=0;while 1y=3/(x+2);if abs(y-x)<0.000001break;else x=y;endendoutput=[y]; end3、编写一M函数,实现212!!nxx xe xn=+++++L L近似计算指数,其中x为函数参数输入,当n+1步与n步的结果误差小于0.00001时停止,分别用for和while 结构实现。
(完整word版)MatLab代码大全
第2章图像获取2.3.2 二维连续傅里叶变换例2.2figure(1); %建立图形窗口1[u,v] = meshgrid(-1:0.01:1); %生成二维频域网格F1 = abs(sinc(u.*pi));F2 = abs(sinc(v.*pi));F=F1.*F2; %计算幅度频谱F=|F(u,v)|surf(u,v,F); %显示幅度频谱,如图2.3(b)shading interp; %平滑三维曲面上的小格axis off; %关闭坐标系figure(2); %建立图形窗口2F1=histeq(F); %扩展F的对比度以增强视觉效果imshow(F1); %用图像来显示幅度频谱,如图2.3(c)第3章图像变换3.4.4 二维FFT的MATLAB实现例3.2 简单图像及其傅里叶变换MATLAB程序:%建立简单图像d并显示之d = zeros(32,32); %图像大小32⨯32d(13:20,13:20) = 1; %中心白色方块大小为8⨯8figure(1); %建立图形窗口1imshow(d,'notruesize');%显示图像d如图3.5(a)所示%计算傅里叶变换并显示之D = fft2(d); %计算图像d的傅里叶变换,fft2(d) = fft(fft(d).').'figure(2); %建立图形窗口2imshow(abs(D),[-1 5],'notruesize'); %显示图像d的傅里叶变换谱如3.5(b)所示例3.3 MATLAB图像及其傅里叶变换谱MATLAB程序:figure(1);load imdemos saturn2; %装入MA TLAB图像saturn2imshow(saturn2); %显示图像saturn2如图3.6(a)所示figure(2);S= fftshift(fft2(saturn2)); %计算傅里叶变换并移位imshow(log(abs(S)),[ ]); %显示傅里叶变换谱如3.6(b)所示例3.4 真彩图像及其傅里叶变换谱MATLAB程序:figure(1);A=imread('image1.jpg'); %装入真彩图像,见图1.1(b)B=rgb2gray(A); %将真彩图像转换为灰度图像imshow(B); %显示灰度图像如图3.7(a)所示C=fftshift(fft2(B)); %计算傅里叶变换并移位figure(2);imshow(log(abs(C)),[ ]); %显示傅里叶变换谱如3.7(b)所示3.5.4 离散余弦变换的MATLAB实现例3.5 计算并显示真彩图像余弦变换的MATLAB程序如下:RGB=imread('image2.jpg'); %装入真彩图像figure(1);imshow(RGB); %显示彩色图像GRAY=rgb2gray(RGB); %将真彩图像转换为灰度图像figure(2);imshow(GRAY); %显示灰度图像如图3.10(a)所示DCT=dct2(GRAY); %进行余弦变换figure(3);imshow(log(abs(DCT)),[ ]); %显示余弦变换如图3.10(b)所示。
practical matlab deep learning 源代码
practical matlab deep learning 源代码在编写MATLAB 深度学习源代码时,我们需要了解一些基本概念和步骤。
在本文中,我将为您解释如何编写一个实用的MATLAB 深度学习源代码,并为您提供一个简单的示例。
深度学习是一种机器学习方法,通过构建人工神经网络模型来模拟和解决复杂的问题。
MATLAB 是一个功能强大的编程环境,它提供了许多有用的工具箱和函数来支持深度学习任务。
编写MATLAB 深度学习源代码需要以下步骤:1. 确定问题和数据集:首先,我们需要确定要解决的问题和相应的数据集。
例如,您可能想要开发一个图像分类器,用于将图像分为不同的类别。
2. 数据预处理与特征提取:在开始训练模型之前,通常需要对数据进行预处理和特征提取。
这可能包括图像缩放、标准化、去噪、平衡数据集等。
MATLAB 提供了许多函数和工具箱,例如Image Processing Toolbox 和Signal Processing Toolbox,可以帮助您进行这些操作。
3. 构建神经网络模型:接下来,您需要构建一个神经网络模型。
在MATLAB 中,您可以使用深度学习工具箱来构建不同类型的网络,例如卷积神经网络(CNN)或循环神经网络(RNN)。
您可以选择在网络中添加不同的层(例如卷积层、池化层、全连接层等)来构建适合您问题的模型。
4. 配置训练参数:在训练模型之前,您需要配置一些训练参数,例如学习率、迭代次数、批量大小等。
这些参数的选择可能会对模型的性能产生重要影响。
MATLAB 提供了许多优化器和训练算法,例如随机梯度下降(SGD)和反向传播(backpropagation),可帮助您进行模型训练。
5. 模型训练与评估:一旦您配置了训练参数,就可以使用MATLAB 进行模型的训练。
通过将输入数据和相应的标签传递给模型,可以通过迭代优化网络参数来训练模型。
在训练过程中,您可以跟踪模型的训练损失和准确率等指标。
Matlab100个实例程序
程序代码:(代码标记[code]...[/code] ) 1-32是:图形应用篇33-66是:界面设计篇67-84是:图形处理篇85-100是:数值分析篇实例1:三角函数曲线(1)function shili01h0=figure('toolbar','none',...'position',[198****0300],...'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');h3=[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)xlabel('实部','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实例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轴');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实例21:PEAKS函数曲线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轴');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****8468],... '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 on'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,',...];'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],...'background','w',...'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,',...'delete(h),',...'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菜单的应用h0=figure('toolbar','none',...'position',[200 150 450 250],...'name','实例40');h1=uimenu(gcf,'label','函数');h11=uimenu(h1,'label','轮廓图',...'callback',[...'set(h31,''checked'',''on''),',...'set(h32,''checked'',''off''),',...'[x,y,z]=peaks;,',...'contour3(x,y,z,30)']);h12=uimenu(h1,'label','高斯分布',...。
matlab十个简单案例编写
matlab十个简单案例编写1. 求解线性方程组线性方程组是数学中常见的问题之一,而MATLAB提供了用于求解线性方程组的函数。
例如,我们可以使用"linsolve"函数来求解以下线性方程组:2x + 3y = 74x - 2y = 2代码如下所示:A = [2, 3; 4, -2];B = [7; 2];X = linsolve(A, B);disp(X);解释:上述代码定义了一个2x2的矩阵A和一个2x1的矩阵B,分别表示线性方程组的系数矩阵和常数向量。
然后,使用linsolve函数求解线性方程组,结果存储在X中,并通过disp函数打印出来。
运行代码后,可以得到x=2和y=1的解。
2. 求解非线性方程除了线性方程组外,MATLAB还可以用于求解非线性方程。
例如,我们可以使用"fzero"函数求解以下非线性方程:x^2 + 2x - 3 = 0代码如下所示:fun = @(x) x^2 + 2*x - 3;x0 = 0;x = fzero(fun, x0);disp(x);解释:上述代码定义了一个匿名函数fun,表示非线性方程。
然后,使用fzero函数传入fun和初始值x0来求解非线性方程的根,并通过disp函数打印出来。
运行代码后,可以得到x=1的解。
3. 绘制函数图像MATLAB提供了强大的绘图功能,可以帮助我们可视化函数的形状和特征。
例如,我们可以使用"plot"函数绘制以下函数的图像:y = cos(x)代码如下所示:x = linspace(0, 2*pi, 100);y = cos(x);plot(x, y);解释:上述代码首先使用linspace函数生成一个从0到2π的100个等间距点的向量x,然后计算对应的cos值,并存储在向量y中。
最后,使用plot函数将x和y作为横纵坐标绘制出函数图像。
运行代码后,可以看到cos函数的周期性波动图像。
Matlab源程序代码
正弦波的源程序:(一),用到的函数1,f2t函数function x=f2t(X)global dt df t f T N%x=f2t(X)%x为时域的取样值矢量%X为x的傅氏变换%X与x长度相同并为2的整幂%本函数需要一个全局变量dt(时域取样间隔) X=[X(N/2+1:N),X(1:N/2)];x=ifft(X)/dt;end2,t2f函数。
function X=t2f(x)global dt df N t f T%X=t2f(x)%x为时域的取样值矢量%X为x的傅氏变换%X与x长度相同,并为2的整幂。
%本函数需要一个全局变量dt(时域取样间隔) H=fft(x);X=[H(N/2+1:N),H(1:N/2)]*dt;end(二),主程序。
1,%(1)绘出正弦信号波形及频谱global dt df t f Nclose allk=input('取样点数=2^k, k取10摆布');if isempty(k), k=10; endf0=input('f0=取1(kz)摆布');if isempty(f0), f0=1; endN=2^k;dt=0.01; %msdf=1/(N*dt); %KHzT=N*dt; %截短期Bs=N*df/2; %系统带宽f=[-Bs+df/2:df:Bs]; %频域横坐标t=[-T/2+dt/2:dt:T/2]; %时域横坐标s=sin(2*pi*f0*t); %输入的正弦信号S=t2f(s); %S是s的傅氏变换a=f2t(S); %a是S的傅氏反变换a=real(a);as=abs(S);subplot(2,1,1) %输出的频谱plot(f,as,'b');gridaxis([-2*f0,+2*f0,min(as),max(as)])xlabel('f (KHz)')ylabel('|S(f)| (V/KHz)') %figure(2)subplot(2,1,2)plot(t,a,'black') %输出信号波形画图gridaxis([-2/f0,+2/f0,-1.5,1.5])xlabel('t(ms)')ylabel('a(t)(V)')gtext('频谱图')最佳基带系统的源程序:(一),用到的函数f2t函数和t2f函数。
matlab代码大全
MATLAB主要命令汇总MATLAB函数参考附录1。
1 管理用命令函数名功能描述函数名功能描述addpath 增加一条搜索路径 rmpath 删除一条搜索路径demo 运行Matlab演示程序 type 列出.M文件doc 装入超文本文档 version 显示Matlab的版本号help 启动联机帮助 what 列出当前目录下的有关文件lasterr 显示最后一条信息 whatsnew 显示Matlab的新特性lookfor 搜索关键词的帮助 which 造出函数与文件所在的目录path 设置或查询Matlab路径附录1。
2管理变量与工作空间用命令函数名功能描述函数名功能描述clear 删除内存中的变量与函数 pack 整理工作空间内存disp 显示矩阵与文本 save 将工作空间中的变量存盘length 查询向量的维数 size 查询矩阵的维数load 从文件中装入数据 who,whos 列出工作空间中的变量名附录1.3文件与操作系统处理命令函数名功能描述函数名功能描述cd 改变当前工作目录 edit 编辑。
M文件delete 删除文件 matlabroot 获得Matlab的安装根目录diary 将Matlab运行命令存盘 tempdir 获得系统的缓存目录dir 列出当前目录的内容 tempname 获得一个缓存(temp)文件!执行操作系统命令附录1.4窗口控制命令函数名功能描述函数名功能描述echo 显示文件中的Matlab中的命令 more 控制命令窗口的输出页面format 设置输出格式附录1。
5启动与退出命令函数名功能描述函数名功能描述matlabrc 启动主程序 quit 退出Matlab环境startup Matlab自启动程序附录2 运算符号与特殊字符附录2.1运算符号与特殊字符函数名功能描述函数名功能描述+ 加 .。
续行标志—减,分行符(该行结果不显示)*矩阵乘;分行符(该行结果显示)。
matlab相关代码
matlab相关代码Matlab是一种高级技术计算语言和交互式环境,广泛应用于科学、工程和金融等领域。
它具有强大的数学和图形处理能力,可以快速处理大量数据和进行复杂的算法分析。
以下是一些常用的Matlab相关代码:1. 矩阵操作Matlab中的矩阵操作非常方便,可以使用以下代码实现:a = [1 2 3; 4 5 6; 7 8 9]; % 定义一个3x3的矩阵b = [4 5 6; 7 8 9; 10 11 12]; % 定义另一个3x3的矩阵c = a + b; % 矩阵加法d = a - b; % 矩阵减法e = a * b; % 矩阵乘法f = a .* b; % 矩阵对应元素相乘g = a' % 矩阵转置2. 绘图Matlab中的绘图功能非常强大,可以使用以下代码实现:x = 0:0.1:2*pi; % 定义x轴的范围y = sin(x); % 定义y轴的值plot(x,y); % 绘制sin函数图像xlabel('x'); % 设置x轴标签ylabel('y'); % 设置y轴标签title('sin函数图像'); % 设置图像标题grid on; % 显示网格线3. 数据处理Matlab中的数据处理功能非常强大,可以使用以下代码实现:data = [1 2 3 4 5 6 7 8 9]; % 定义一个数据数组mean_data = mean(data); % 计算平均值std_data = std(data); % 计算标准差max_data = max(data); % 计算最大值min_data = min(data); % 计算最小值median_data = median(data); % 计算中位数4. 机器学习Matlab中的机器学习功能非常强大,可以使用以下代码实现:load fisheriris; % 加载鸢尾花数据集X = meas(:,1:2); % 取前两个特征Y = species; % 取标签svmModel = fitcsvm(X,Y); % 训练SVM模型svmModel.ClassNames % 显示类别名称svmModel.Beta % 显示模型系数总之,Matlab是一种非常强大的工具,可以帮助科学家、工程师和金融分析师等快速处理数据和进行复杂的算法分析。
matlab智能算法代码
matlab智能算法代码MATLAB是一种功能强大的数值计算和科学编程软件,它提供了许多智能算法的实现。
下面是一些常见的智能算法及其在MATLAB中的代码示例:1. 遗传算法(Genetic Algorithm):MATLAB中有一个专门的工具箱,称为Global Optimization Toolbox,其中包含了遗传算法的实现。
以下是一个简单的遗传算法示例代码:matlab.% 定义目标函数。
fitness = @(x) x^2;% 设置遗传算法参数。
options = gaoptimset('Display', 'iter','PopulationSize', 50);% 运行遗传算法。
[x, fval] = ga(fitness, 1, options);2. 粒子群优化算法(Particle Swarm Optimization):MATLAB中也有一个工具箱,称为Global Optimization Toolbox,其中包含了粒子群优化算法的实现。
以下是一个简单的粒子群优化算法示例代码:matlab.% 定义目标函数。
fitness = @(x) x^2;% 设置粒子群优化算法参数。
options = optimoptions('particleswarm', 'Display','iter', 'SwarmSize', 50);% 运行粒子群优化算法。
[x, fval] = particleswarm(fitness, 1, [], [], options);3. 支持向量机(Support Vector Machine):MATLAB中有一个机器学习工具箱,称为Statistics and Machine Learning Toolbox,其中包含了支持向量机的实现。
matlab实验代码(总)
matlab实验代码(总)% 使⽤两种⽅法,创建⼀稀疏矩阵% 使⽤函数sparse,可以⽤⼀组⾮零元素直接创建⼀个稀疏矩阵。
该函数调⽤格式为:% S=sparse(i,j,s,m,n)% 其中i和j都为⽮量,分别是指矩阵中⾮零元素的⾏号与列号,% s是⼀个全部为⾮零元素⽮量,元素在矩阵中排列的位置为(i,j)% m为输出的稀疏矩阵的⾏数,n为输出的稀疏矩阵的列数。
%⽅法1A9=[0 0 1;0 3 0;2 4 0]B9=sparse(A9)C9=full(B9)%⽅法2A10=sparse([1 3 2 4],[2 3 1 4],[1 2 3 4],4,4)C10=full(A10)A11=[1 2 3];B11=[4 5 6];C11=3.^A11D11=A11.^B11%使⽤函数,实现矩阵左旋90°或右旋90°的功能。
A=[ 1 2 3 ; 4 5 6 ; 7 8 9 ]B=rot90(A,1)C=rot90(A,-1)%求S=2^0+2^1+2^2+2^3+2^4+……+2^10的值(提⽰:利⽤求和函数与累乘积函数。
)A=2*ones(1,10)%10个2B=cumprod(A)%平⽅C=sum(B)+1%加上2^0%建⽴⼀个字符串向量,删除其中的⼤写字母(提⽰:利⽤find函数和空矩阵。
)str='AAAbCcd'b=find(str>='A' & str<='Z');str(b)=[];% 输⼊⼀个百分制成绩,要求输出成绩等级A、B、C、D、E。
其中90分~100分为A,80分~89分为B,70分~79为C,60分~69分为D,60分以下为E。
switch(score)case num2cell(90:0.5:100)disp(['成绩等级为:A']);case num2cell(80:0.5:89.5)disp(['成绩等级为:B']);case num2cell(70:0.5:79.5)disp(['成绩等级为:C']);case num2cell(60:0.5:69.5)disp(['成绩等级为:D']);case num2cell(0:0.5:59.5)disp(['成绩等级为:E']);otherwisedisp(['输⼊成绩不合理!']);end%设计程序,完成两位数的加、减、乘、除四则运算,%即产⽣两个两位随机整数,再输⼊⼀个运算符号,做相应的运算,显⽰相应的结果,并要求结果显⽰类似于“a=x+y=34”。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.图像反转MATLAB程序实现如下:I=imread('xian.bmp');J=double(I);J=-J+(256-1); %图像反转线性变换H=uint8(J);subplot(1,2,1),imshow(I);subplot(1,2,2),imshow(H);2.灰度线性变换MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);axis on; %显示坐标系I1=rgb2gray(I);subplot(2,2,2),imshow(I1);title('灰度图像');axis([50,250,50,200]);axis on; %显示坐标系J=imadjust(I1,[0.1 0.5],[]); %局部拉伸,把[0.1 0.5]内的灰度拉伸为[0 1] subplot(2,2,3),imshow(J);title('线性变换图像[0.1 0.5]');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系K=imadjust(I1,[0.3 0.7],[]); %局部拉伸,把[0.3 0.7]内的灰度拉伸为[0 1] subplot(2,2,4),imshow(K);title('线性变换图像[0.3 0.7]');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系3.非线性变换MATLAB程序实现如下:I=imread('xian.bmp');I1=rgb2gray(I);subplot(1,2,1),imshow(I1);title('灰度图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系J=double(I1);J=40*(log(J+1));H=uint8(J);subplot(1,2,2),imshow(H);title('对数变换图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系4.直方图均衡化MATLAB程序实现如下:I=imread('xian.bmp');I=rgb2gray(I);figure;subplot(2,2,1);imshow(I);subplot(2,2,2);imhist(I);I1=histeq(I);figure;subplot(2,2,1);imshow(I1);subplot(2,2,2);imhist(I1);5.线性平滑滤波器用MATLAB实现领域平均法抑制噪声程序:I=imread('xian.bmp');subplot(231)imshow(I)title('原始图像')I=rgb2gray(I);I1=imnoise(I,'salt & pepper',0.02);subplot(232)imshow(I1)title('添加椒盐噪声的图像')k1=filter2(fspecial('average',3),I1)/255; %进行3*3模板平滑滤波k2=filter2(fspecial('average',5),I1)/255; %进行5*5模板平滑滤波k3=filter2(fspecial('average',7),I1)/255; %进行7*7模板平滑滤波k4=filter2(fspecial('average',9),I1)/255; %进行9*9模板平滑滤波subplot(233),imshow(k1);title('3*3模板平滑滤波');subplot(234),imshow(k2);title('5*5模板平滑滤波');subplot(235),imshow(k3);title('7*7模板平滑滤波');subplot(236),imshow(k4);title('9*9模板平滑滤波');6.中值滤波器用MATLAB实现中值滤波程序如下:I=imread('xian.bmp');I=rgb2gray(I);J=imnoise(I,'salt&pepper',0.02);subplot(231),imshow(I);title('原图像');subplot(232),imshow(J);title('添加椒盐噪声图像');k1=medfilt2(J); %进行3*3模板中值滤波k2=medfilt2(J,[5,5]); %进行5*5模板中值滤波k3=medfilt2(J,[7,7]); %进行7*7模板中值滤波k4=medfilt2(J,[9,9]); %进行9*9模板中值滤波subplot(233),imshow(k1);title('3*3模板中值滤波');subplot(234),imshow(k2);title('5*5模板中值滤波');subplot(235),imshow(k3);title('7*7模板中值滤波');subplot(236),imshow(k4);title('9*9模板中值滤波');7.用Sobel算子和拉普拉斯对图像锐化:I=imread('xian.bmp');subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(2,2,2),imshow(I1);title('二值图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系H=fspecial('sobel'); %选择sobel算子J=filter2(H,I1); %卷积运算subplot(2,2,3),imshow(J);title('sobel算子锐化图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系h=[0 1 0,1 -4 1,0 1 0]; %拉普拉斯算子J1=conv2(I1,h,'same'); %卷积运算subplot(2,2,4),imshow(J1);title('拉普拉斯算子锐化图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系8.梯度算子检测边缘用MATLAB实现如下:I=imread('xian.bmp');subplot(2,3,1);imshow(I);title('原始图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(2,3,2);imshow(I1);title('二值图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I2=edge(I1,'roberts');figure;subplot(2,3,3);imshow(I2);title('roberts算子分割结果');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I3=edge(I1,'sobel');subplot(2,3,4);imshow(I3);title('sobel算子分割结果');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I4=edge(I1,'Prewitt');subplot(2,3,5);imshow(I4);title('Prewitt算子分割结果');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系9.LOG算子检测边缘用MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1);imshow(I);title('原始图像');I1=rgb2gray(I);subplot(2,2,2);imshow(I1);title('灰度图像');I2=edge(I1,'log'); subplot(2,2,3);imshow(I2);title('log算子分割结果');10.Canny算子检测边缘用MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1);imshow(I);title('原始图像')I1=rgb2gray(I);subplot(2,2,2);imshow(I1);title('灰度图像');I2=edge(I1,'canny');subplot(2,2,3);imshow(I2);title('canny算子分割结果');11.边界跟踪(bwtraceboundary函数)clcclear allI=imread('xian.bmp');figureimshow(I);title('原始图像');I1=rgb2gray(I); %将彩色图像转化灰度图像threshold=graythresh(I1); %计算将灰度图像转化为二值图像所需的门限BW=im2bw(I1, threshold); %将灰度图像转化为二值图像figureimshow(BW);title('二值图像');dim=size(BW);col=round(dim(2)/2)-90; %计算起始点列坐标row=find(BW(:,col),1); %计算起始点行坐标connectivity=8;num_points=180;contour=bwtraceboundary(BW,[row,col],'N',connectivity,num_points); %提取边界figureimshow(I1);hold on;plot(contour(:,2),contour(:,1), 'g','LineWidth' ,2);title('边界跟踪图像');12.Hough变换I= imread('xian.bmp');rotI=rgb2gray(I);subplot(2,2,1);imshow(rotI);title('灰度图像');axis([50,250,50,200]);grid on;axis on;BW=edge(rotI,'prewitt');subplot(2,2,2);imshow(BW);title('prewitt算子边缘检测后图像');axis([50,250,50,200]);grid on;axis on;[H,T,R]=hough(BW);subplot(2,2,3);imshow(H,[],'XData',T,'YData',R,'InitialMagnification','fit'); title('霍夫变换图');xlabel('\theta'),ylabel('\rho');axis on , axis normal, hold on;P=houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));x=T(P(:,2));y=R(P(:,1));plot(x,y,'s','color','white');lines=houghlines(BW,T,R,P,'FillGap',5,'MinLength',7);subplot(2,2,4);,imshow(rotI);title('霍夫变换图像检测');axis([50,250,50,200]);grid on;axis on;hold on;max_len=0;for k=1:length(lines)xy=[lines(k).point1;lines(k).point2];plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');len=norm(lines(k).point1-lines(k).point2);if(len>max_len)max_len=len;xy_long=xy;endendplot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');13.直方图阈值法用MATLAB实现直方图阈值法:I=imread('xian.bmp');I1=rgb2gray(I);figure;subplot(2,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系[m,n]=size(I1);%测量图像尺寸参数GP=zeros(1,256);%预创建存放灰度出现概率的向量for k=0:255GP(k+1)=length(find(I1==k))/(m*n); %计算每级灰度出现的概率,将其存入GP中相应位置endsubplot(2,2,2),bar(0:255,GP,'g')%绘制直方图title('灰度直方图')xlabel('灰度值')ylabel('出现概率')I2=im2bw(I,150/255);subplot(2,2,3),imshow(I2);title('阈值150的分割图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I3=im2bw(I,200/255); %subplot(2,2,4),imshow(I3);title('阈值200的分割图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系14. 自动阈值法:Otsu法用MATLAB实现Otsu算法:clcclear allI=imread('xian.bmp');subplot(1,2,1),imshow(I);title('原始图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系level=graythresh(I); %确定灰度阈值BW=im2bw(I,level);subplot(1,2,2),imshow(BW);title('Otsu法阈值分割图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系15.膨胀操作I=imread('xian.bmp'); %载入图像I1=rgb2gray(I);subplot(1,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系se=strel('disk',1); %生成圆形结构元素I2=imdilate(I1,se); %用生成的结构元素对图像进行膨胀subplot(1,2,2);imshow(I2);title('膨胀后图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系16.腐蚀操作MATLAB实现腐蚀操作I=imread('xian.bmp'); %载入图像I1=rgb2gray(I);subplot(1,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系se=strel('disk',1); %生成圆形结构元素I2=imerode(I1,se); %用生成的结构元素对图像进行腐蚀subplot(1,2,2);imshow(I2);title('腐蚀后图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系17.开启和闭合操作用MATLAB实现开启和闭合操作I=imread('xian.bmp'); %载入图像subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);axis on; %显示坐标系I1=rgb2gray(I);subplot(2,2,2),imshow(I1);title('灰度图像');axis([50,250,50,200]);axis on; %显示坐标系se=strel('disk',1); %采用半径为1的圆作为结构元素I2=imopen(I1,se); %开启操作I3=imclose(I1,se); %闭合操作subplot(2,2,3),imshow(I2);title('开启运算后图像');axis([50,250,50,200]);axis on; %显示坐标系subplot(2,2,4),imshow(I3);title('闭合运算后图像');axis([50,250,50,200]);axis on; %显示坐标系18.开启和闭合组合操作I=imread('xian.bmp'); %载入图像subplot(3,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);axis on; %显示坐标系I1=rgb2gray(I);subplot(3,2,2),imshow(I1);title('灰度图像');axis([50,250,50,200]);axis on; %显示坐标系se=strel('disk',1);I2=imopen(I1,se); %开启操作I3=imclose(I1,se); %闭合操作subplot(3,2,3),imshow(I2);title('开启运算后图像');axis([50,250,50,200]);axis on; %显示坐标系subplot(3,2,4),imshow(I3);title('闭合运算后图像');axis([50,250,50,200]);axis on; %显示坐标系se=strel('disk',1);I4=imopen(I1,se);I5=imclose(I4,se);subplot(3,2,5),imshow(I5); %开—闭运算图像title('开—闭运算图像');axis([50,250,50,200]);axis on; %显示坐标系I6=imclose(I1,se);I7=imopen(I6,se);subplot(3,2,6),imshow(I7); %闭—开运算图像title('闭—开运算图像');axis([50,250,50,200]);axis on; %显示坐标系利用MATLAB实现如下:I=imread('xian.bmp'); %载入图像subplot(1,3,1),imshow(I);title('原始图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(1,3,2),imshow(I1);title('二值化图像');axis([50,250,50,200]);grid on; %显示网格线axis on; %显示坐标系I2=bwperim(I1); %获取区域的周长subplot(1,3,3),imshow(I2);title('边界周长的二值图像');axis([50,250,50,200]);grid on;axis on;利用MATLAB实现如下:I=imread('xian.bmp');subplot(2,2,1),imshow(I);title('原始图像');axis([50,250,50,200]);axis on;I1=im2bw(I);subplot(2,2,2),imshow(I1);title('二值图像');axis([50,250,50,200]);axis on;I2=bwmorph(I1,'skel',1);subplot(2,2,3),imshow(I2);title('1次骨架提取');axis([50,250,50,200]);axis on;I3=bwmorph(I1,'skel',2);subplot(2,2,4),imshow(I3);title('2次骨架提取');axis([50,250,50,200]);axis on;21.直接提取四个顶点坐标I = imread('xian.bmp');I = I(:,:,1);BW=im2bw(I);figureimshow(~BW)[x,y]=getpts(注:文档可能无法思考全面,请浏览后下载,供参考。