matlab基本语句

合集下载

matlab常用指令

matlab常用指令

matlab常用指令MATLAB是一款非常实用的科学计算软件,在使用过程中,一些常用的指令是非常必要的。

在本篇文章中,我们将会介绍MATLAB常用指令,以使你更加熟练掌握MATLAB的使用。

一、基本数学运算+ 加- 减* 乘/ 除^ 幂(指数)sqrt 平方根exp 取指数log 取自然对数log10 取以10为底的对数sin 正弦cos 余弦tan 正切asin 反正弦acos 反余弦atan 反正切abs 绝对值rem 模运算fix 向零取整floor 向负无穷取整ceil 向正无穷取整round 四舍五入mod 取摸余数二、变量与矩阵1、赋值:通过等号将数值赋给变量,如:a=3;b=2.1;c=2+3i;2、数列:建立一个等差数组,例如:d=1:10; %1到10的等差数列e=linspace(0,2*pi,100); %0到2*pi之间的100个等间距点 a=[1 2 3;4 5 6;7 8 9];b=zeros(2,3);c=ones(3,2);d=rand(3,3);e=eye(4);4、矩阵元素操作:通过下标访问矩阵中的元素,例如:a(1,2) %输出a矩阵第一行第二列的元素b(2,3)=7 %将b矩阵第二行第三列的元素赋为75、矩阵运算:矩阵加减乘除,如:a+b %对应元素相加a-b %对应元素相减a*b %矩阵乘法a/b %矩阵除法a' %矩阵转置6、矩阵函数:除了使用基本操作外,还能使用各种矩阵相关函数完成矩阵计算,例如:inv(a) %矩阵求逆det(a) %矩阵求行列式trace(a) %矩阵求迹eig(a) %求特征值rank(a) %矩阵的秩size(a) %返回矩阵的大小max(a) %求矩阵元素最大值min(a) %求矩阵元素最小值sum(a) %求矩阵元素的和prod(a) %求矩阵所有元素的乘积mean(a) %求矩阵元素的平均值三、绘图1、二维绘图:绘制二维函数的曲线、散点图等,例如:x=linspace(-3,3,100); %生成-3到3之间的100个等间距点y=sin(x);plot(x,y); %绘制正弦函数曲线plot(x,y,'r--'); %绘制红色的正弦函数曲线,形状为虚线xlabel('x values');ylabel('y values');title('sine function');grid on;四、数据处理1、数据导入:在MATLAB中,可以通过各种方式将数据导入,如:a=load('filename.txt'); %从文件中载入数据b=xlsread('filename.xls'); %从Excel文件中载入数据五、编程1、条件语句:通过条件语句实现程序的分支结构,例如:if(a<0)disp('a is negative');elseif(a==0)disp('a is zero');elsedisp('a is positive');endfor i=1:10disp(i);end3、函数:在MATLAB中,可以自定义函数,函数调用格式为:function [out1,out2,...]=function_name(in1,in2,...)%函数说明%计算过程end4、脚本:在MATLAB中,脚本是一些命令或函数的集合,可以将脚本保存到文件中执行,例如:%脚本说明a=1;b=2;c=a+b;disp(c);以上便是MATLAB一些常用指令的详细介绍。

matlab m 编程语言

matlab m 编程语言

matlab m 编程语言Matlab M编程语言是一种高级的数值计算和编程环境,其提供了丰富的函数和工具箱,用于科学计算、数据分析、图像处理等各个领域。

本文将介绍Matlab M编程语言的基本语法和常用功能。

一、基本语法Matlab M编程语言的基本语法类似于其他编程语言,包括变量的定义和赋值、条件语句、循环语句等。

下面以一个简单的例子来说明基本语法:```matlab% 定义变量a = 10;b = 20;% 条件语句if a > bdisp('a大于b');elseif a < bdisp('a小于b');elsedisp('a等于b');end% 循环语句for i = 1:5disp(i);end```二、常用函数和工具箱Matlab M编程语言提供了丰富的函数和工具箱,用于各种科学计算和数据处理任务。

下面列举一些常用的函数和工具箱:1. 统计工具箱:用于统计分析和数据建模,包括描述统计、假设检验、回归分析等功能。

2. 图像处理工具箱:用于图像处理和计算机视觉任务,包括图像滤波、边缘检测、图像分割等功能。

3. 信号处理工具箱:用于信号处理和数字信号处理任务,包括滤波、频谱分析、时频分析等功能。

4. 控制系统工具箱:用于控制系统分析和设计,包括传递函数表示、稳定性分析、控制器设计等功能。

5. 优化工具箱:用于优化问题的建模和求解,包括线性规划、非线性规划、整数规划等功能。

三、应用实例Matlab M编程语言在科学计算和工程应用中有广泛的应用。

下面举两个实际应用的例子:1. 图像处理:利用Matlab M编程语言中的图像处理工具箱,可以对图像进行各种处理和分析。

例如,可以对医学影像进行图像增强,提取感兴趣区域,进行图像分割等操作。

2. 机器学习:Matlab M编程语言提供了丰富的机器学习工具箱,可以用于分类、聚类、回归等任务。

例如,可以利用支持向量机对数据进行分类,利用神经网络进行回归分析等。

matlab条件语句

matlab条件语句

matlab条件语句Matlab一种数学软件,常用于数值计算、可视化和编程。

它是一个功能强大的工具,可以帮助从事数学、工程和科学领域的研究人员进行分析。

Matlab 中的条件语句是一种语句,可以为程序提供灵活性和控制,可以根据需要执行代码块。

Matlab 中有三种基本条件语句:if-else,switch-casetry-catch。

这些条件语句允许程序员构建复杂的程序,以便在不同情况下执行不同代码。

if句是 Matlab 中最常用的一种条件语句,它的语法如下:if件一组 Matlab句endif-else句允许程序员在特定条件下执行特定的Matlab句。

它的语法如下:if件一组 Matlab句else一组其他 Matlab句endswitch-case句是另一种复杂条件语句,它允许程序员指定不同的代码块,根据不同的情况来执行它们,这种情况可以是字符串、数字或别的变量类型。

它的语法如下:switch件case1一组 Matlab句case2一组 Matlab句casen一组 Matlab句end最后,Matlab持一种异常处理语句,即 try-catch。

这种语句允许程序员在程序运行过程中捕获并处理错误。

它的语法如下:try一组 Matlab句catch一组 Matlab句end使用 Matlab 中的条件语句可以提高程序的效能和灵活性,使我们能够在不同的情况下执行不同的代码段,实现更强大的功能。

条件语句可以使程序更容易维护,更易于理解和调试。

Matlab一种强大的数学软件,灵活的条件语句可以使程序更具灵活性和可扩展性。

学习使用 Matlab条件语句可以让程序员更有效地完成自己的工作。

matlab 指令大全

matlab 指令大全

分享我的分享当前分享返回分享首页»分享matlab命令,应该很全了!来源:李家叶的日志matlab命令一、常用对象操作:除了一般windows窗口的常用功能键外。

1、!dir 可以查看当前工作目录的文件。

!dir& 可以在dos状态下查看。

2、who 可以查看当前工作空间变量名,whos 可以查看变量名细节。

3、功能键:功能键快捷键说明方向上键Ctrl+P 返回前一行输入方向下键Ctrl+N 返回下一行输入方向左键Ctrl+B 光标向后移一个字符方向右键Ctrl+F 光标向前移一个字符Ctrl+方向右键Ctrl+R 光标向右移一个字符Ctrl+方向左键Ctrl+L 光标向左移一个字符home Ctrl+A 光标移到行首End Ctrl+E 光标移到行尾Esc Ctrl+U 清除一行Del Ctrl+D 清除光标所在的字符Backspace Ctrl+H 删除光标前一个字符Ctrl+K 删除到行尾Ctrl+C 中断正在执行的命令4、clc可以命令窗口显示的内容,但并不清除工作空间。

二、函数及运算1、运算符:+:加,-:减,*:乘,/:除,\:左除^:幂,‘:复数的共轭转置,():制定运算顺序。

2、常用函数表:sin( ) 正弦(变量为弧度)Cot( ) 余切(变量为弧度)sind( ) 正弦(变量为度数)Cotd( ) 余切(变量为度数)asin( ) 反正弦(返回弧度)acot( ) 反余切(返回弧度)Asind( ) 反正弦(返回度数)acotd( ) 反余切(返回度数)cos( ) 余弦(变量为弧度)exp( ) 指数cosd( ) 余弦(变量为度数)log( ) 对数acos( ) 余正弦(返回弧度)log10( ) 以10为底对数acosd( ) 余正弦(返回度数)sqrt( ) 开方tan( ) 正切(变量为弧度)realsqrt( ) 返回非负根tand( ) 正切(变量为度数)abs( ) 取绝对值atan( ) 反正切(返回弧度)angle( ) 返回复数的相位角atand( ) 反正切(返回度数)mod(x,y) 返回x/y的余数sum( ) 向量元素求和3、其余函数可以用help elfun和help specfun命令获得。

常用matlab语句

常用matlab语句
setdiff:集合差集
setxor:集合异或(不在交集中的元素)
union:两个集合的并
unique:返回向量作为一个集合所有元素(去掉相同元素)
14、代数式因式分解,展开,极限,倒数,级数求和,泰勒级数展开
>>syms x y a b c t
>>E1 = expand((x-2)*(x-4)*(y-t))//因式展开
3、将向量坐标在matlab里作图:
x=xlsread('C:\Documents and Settings\Administrator\桌面\school\GIS\新建Microsoft Excel工作表.xls',1,'A1:a1000');
y=xlsread('C:\Documents and Settings\Administrator\桌面\school\GIS\新建Microsoft Excel工作表.xls',1,'b1:b1000');
2 3 4 6 7 8
2 3 5 6 7 8
2 4 5 6 7 8
3 4 5 6 7 8
19、设n个人中每个人的生日在一年365天中任一天是等可能的。 求当n为23,40,64时,这n个人中至少有两人生日相同的概率各为多少?
>> n=23;
>> p=1-nchoosek(365,n)*factorial(n)/365^n
Title(‘plot of sin(x)/x’);
Grid on;
fplot与ezplot相类似,但更加精确。前两个参数与函数ezplot中的相同,但是数fplot还有其他优点
1.函数fplot是适应性的,它意味着在自变量范围内函数突然变化显示更多的点。

matlab基本语句及语法

matlab基本语句及语法

matlab基本语句及语法一、基本语法1. 变量定义与赋值:在MATLAB中,可以使用等号(=)将一个数值或表达式赋值给一个变量。

例如:a = 5; 表示将数值5赋值给变量a。

2. 注释:在MATLAB中,可以使用百分号(%)来添加注释,以便于代码的阅读和理解。

例如:% 这是一条注释。

3. 函数的定义与调用:在MATLAB中,可以使用关键字function 来定义函数,并使用函数名进行调用。

例如:function result = add(a, b) 表示定义了一个名为add的函数,该函数接受两个参数a 和b,并返回一个结果result。

4. 条件语句:在MATLAB中,可以使用if语句来实现条件判断。

例如:if a > b 表示如果a大于b,则执行if语句块中的代码。

5. 循环语句:在MATLAB中,可以使用for循环和while循环来实现循环操作。

例如:for i = 1:10 表示从1循环到10,每次循环中i 的值递增1。

6. 矩阵的定义与操作:在MATLAB中,可以使用方括号([])来定义矩阵,并使用各种运算符进行矩阵的操作。

例如:A = [1 2; 3 4] 表示定义了一个2x2的矩阵A。

7. 字符串的操作:在MATLAB中,可以使用单引号('')来定义字符串,并使用加号(+)来进行字符串的拼接。

例如:str = 'Hello' + 'World' 表示将字符串'Hello'和'World'进行拼接。

8. 文件的读写:在MATLAB中,可以使用fopen、fread、fwrite 等函数来进行文件的读写操作。

例如:fid = fopen('file.txt', 'w') 表示打开一个名为file.txt的文件,并以写入模式打开。

9. 图形绘制:在MATLAB中,可以使用plot、scatter、histogram等函数来进行图形的绘制。

matlab基础语句句法和举例

matlab基础语句句法和举例

rootsSyntaxDescriptionr = roots(c) returns a column vector whose elements are the roots of the polynomial c. Row vector c contains the coefficients of a polynomial, ordered in descending powers. If c has n+1 components, the polynomial it represents is c1x n+c2x (n-1)+…+c n-1+1.>> c=[ 1 2 3]c =1 2 3>> roots(c)ans =-1.0000 + 1.4142i-1.0000 - 1.4142iexpexpExponentialSyntaxY = exp(X)DescriptionThe exp function is an elementary function that operates element-wise on arrays. Its domain includes complex numbers. Y = exp(X) returns the exponential for each element of Xlog %(注意MA TLAB里log是ln的意思)logNaturallogarithm SyntaxY = log(X)DescriptionThe log function operates element-wise on arrays. Its domain includes complex and negative numbers, which may lead to unexpected results if used unintentionally. Y = log(X) returns the natural logarithm of the elements of X.>> exp(log(1))ans =1反三角函数asinacosnorm 求向量的模或矩阵的范数Vector and matrix normsSyntaxn = norm(A)n = norm(A,p)DescriptionThe norm of a matrix is a scalar that gives some measure of the magnitude of the elements of the matrix.The norm function calculates several different types of matrix norms:n = norm(A) returns the largest singular value of A, max(svd(A)).n = norm(A,p) returns a different kind of norm, depending on the value of p.RemarksNote that norm(x) is the Euclidean length of a vector x. On the other hand, MATLAB uses "length" to denote the number of elements n in a vector. This example uses norm(x)/sqrt(n) to obtain the root-mean-square (RMS) value of an n-element vector x. x = [0 1 2 3]x =0 1 2 3sqrt(0+1+4+9) % Euclidean lengthans =3.7417norm(x)ans =3.7417n = length(x) % Number of elementsn =4rms = 3.7417/2 % rms = norm(x)/sqrt(n)rms =1.8708axis 建立坐标系axis Axis scaling and appearanceSyntaxaxis([xmin xmax ymin ymax])axis([xmin xmax ymin ymax zmin zmax cmin cmax])v = axisaxis autoaxis manualaxis tightaxis fillaxis ijaxis xyaxis equalaxis imageaxis squareaxis vis3daxis normalaxis offaxis onaxis(axes_handles,...)[mode,visibility,direction] = axis('state')Descriptionaxis manipulates commonly used axes properties. (See Algorithm section.)axis([xmin xmax ymin ymax]) sets the limits for the x- and y-axis of the current axes.axis([xmin xmax ymin ymax zmin zmax cmin cmax]) sets the x-, y-, and z-axis limits and the color scaling limits (see caxis) of the current axes.v = axis returns a row vector containing scaling factors for the x-, y-, and z-axis. v has four or six components depending on whether the current axes is 2-D or 3-D, respectively. The returned values are the current axes' XLim, Ylim, and ZLim properties.axis auto sets MATLAB to its default behavior of computing the current axes' limits automatically, based on the minimum and maximum values of x, y, and z data. You can restrict this automaticbehavior to a specific axis. For example, axis 'auto x' computes only the x-axis limits automatically; axis 'auto yz' computes the y- and z-axis limits automatically.axis manual and axis(axis) freezes the scaling at the current limits, so that if hold is on, subsequent plots use the same limits. This sets the XLimMode, YLimMode, and ZLimMode properties to manual.axis tight sets the axis limits to the range of the data.axis fill sets the axis limits and PlotBoxAspectRatio so that the axes fill the position rectangle. This option has an effect only if PlotBoxAspectRatioMode or DataAspectRatioMode are manual. axis ij places the coordinate system origin in the upper-left corner. The i-axis is vertical, with values increasing from top to bottom. The j-axis is horizontal with values increasing from left to right.axis xy draws the graph in the default Cartesian axes format with the coordinate system origin in the lower-left corner. The x-axis is horizontal with values increasing from left to right. The y-axis is vertical with values increasing from bottom to top.axis equal sets the aspect ratio so that the data units are the same in every direction. The aspect ratio of the x-, y-, and z-axis is adjusted automatically according to the range of data units in the x, y, and z directions.axis image is the same as axis equal except that the plot box fits tightly around the data.axis square makes the current axes region square (or cubed when three-dimensional). MATLAB adjusts the x-axis, y-axis, and z-axis so that they have equal lengths and adjusts the increments between data units accordingly.axis vis3d freezes aspect ratio properties to enable rotation of 3-D objects and overrides stretch-to-fill.axis normal automatically adjusts the aspect ratio of the axes and the relative scaling of the data units so that the plot fits the figures shape as best as possible.axis off turns off all axis lines, tick marks, and labels.axis on turns on all axis lines, tick marks, and labels.axis(axes_handles,...) applies the axis command to the specified axes. For example, the following statements:h1 = subplot(221);h2 = subplot(222);axis([h1 h2],'square')set both axes to square. [mode,visibility,direction] = axis('state') returns three strings indicating the current setting of axes properties:magic() 幻方函数magicMagic squareSyntaxM = magic(n)DescriptionM = magic(n) returns an n-by-n matrix constructed from the integers 1 through n^2 with equal row and column sums. The order n must be a scalar greater than or equal to 3.RemarksA magic square, scaled by its magic sum, is doubly stochastic.ExamplesThe magic square of order 3 is M = magic(3)M =8 1 63 5 74 9 2This is called a magic square because the sum of the elements in each column is the same. sum(M) =15 15 15And the sum of the elements in each row, obtained by transposing twice, is the same. sum(M')' =151515This is also a special magic square because the diagonal elements have the same sum. sum(diag(M)) =15The value of the characteristic sum for a magic square of order n is sum(1:n^2)/nwhich, when n = 3, is 15.AlgorithmThere are three different algorithms: n odd n even but not divisible by four n divisible by four To make this apparent, typefor n = 3:20A = magic(n);r(n) = rank(A);endFor n odd, the rank of the magic square is n. For n divisible by 4, the rank is 3. For n even but not divisible by 4, the rank is n/2 + 2.[(3:20)',r(3:20)']ans =3 34 35 56 57 78 39 910 711 1112 313 1314 915 1516 317 1718 1119 1920 3Plotting A for n = 18, 19, 20 shows the characteristic plot for each category.eye 制作单位阵(?)eyeIdentity matrixSyntaxY = eye(n)Y = eye(m,n)Y = eye(size(A))DescriptionY = eye(n) returns the n-by-n identity matrix.Y = eye(m,n) or eye([m n]) returns an m-by-n matrix with 1's on the diagonal and 0's elsewhere. Y = eye(size(A)) returns an identity matrix the same size as A.LimitationsThe identity matrix is not defined for higher-dimensional arrays. The assignment y = eye([2,3,4]) results in an error.>> n=3;y = eye(n)y =1 0 00 1 00 0 1>> n=4;m=9;eye(n,m)ans =1 0 0 0 0 0 0 0 00 1 0 0 0 0 0 0 00 0 1 0 0 0 0 0 00 0 0 1 0 0 0 0 0>>zeros OzerosCreate an array of all zerosSyntaxB = zeros(n)B = zeros(m,n)B = zeros([m n])B = zeros(d1,d2,d3...)B = zeros([d1 d2 d3...])B = zeros(size(A))DescriptionB = zeros(n) returns an n-by-n matrix of zeros. An error message appears if n is not a scalar.B = zeros(m,n) or B = zeros([m n]) returns an m-by-n matrix of zeros.B = zeros(d1,d2,d3...) or B = zeros([d1 d2 d3...]) returns an array of zeros with dimensionsd1-by-d2-by-d3-by-... .B = zeros(size(A)) returns an array the same size as A consisting of all zeros.RemarksThe MATLAB language does not have a dimension statement; MATLAB automatically allocates storage for matrices. Nevertheless, for large matrices, MATLAB programs may execute faster if the zeros function is used to set aside storage for a matrix whose elements are to be generated one at a time, or a row or column at a time.For examplex = zeros(1,n);for i = 1:n, x(i) = i; endtriu 取下三角行列式Upper triangular part of a matrixSyntaxU = triu(X)U = triu(X,k)>> triu(ones(4,4),-1)ans =1 1 1 11 1 1 10 1 1 10 0 1 1>> triu(ones(4,4),1)ans =0 1 1 10 0 1 10 0 0 10 0 0 0>> triu(ones(4,4),0)ans =1 1 1 10 1 1 10 0 1 10 0 0 1A.’矩阵A的转置inv 对矩阵求逆invMatrix inverseSyntaxY = inv(X)DescriptionY = inv(X) returns the inverse of the square matrix X.A warning message is printed if X is badly scaled or nearly singular. In practice, it is seldom necessary to form the explicit inverse of a matrix.A frequent misuse of inv arises when solving the system of linear equations A x=b. One way to solve this is with x = inv(A)*b. A better way, from both an execution time and numerical accuracy standpoint, is to use the matrix division operator x = A\b. This produces the solution usingGaussian elimination, without forming the inverse. See \ and / for further information.例1-9画出函数y = x2cosx 与z = sinx / x 在区间[-6π,6π]上的图像。

matlab的输出语句

matlab的输出语句

matlab的输出语句在编程领域,Matlab是一个颇受欢迎的工具,用于数值计算、数据分析和算法开发。

作为一种高级编程语言,Matlab拥有丰富的功能和强大的输出语句,能够帮助开发者进行结果显示和调试。

本文将介绍Matlab中常用的输出语句,并探讨它们的灵活应用。

Matlab中最基本的输出语句是disp函数。

使用disp函数,我们可以将指定的文本或变量的值显示在Matlab命令窗口中。

例如,当需要输出一段提示文字时,可以调用disp函数,如下所示:```matlabdisp('Welcome to Matlab!');```这将在命令窗口中显示"Welcome to Matlab!"。

除了文本,我们还可以输出变量的值。

例如:```matlabx = 5;disp(x);```这将在命令窗口中显示变量x的值,即数字5。

除了disp函数,Matlab还提供了其他几种输出语句,如fprintf函数和sprintf函数。

这些函数允许我们根据需要格式化输出结果。

fprintf函数用于将格式化文本输出到文件或命令窗口。

它类似于C语言中的printf函数。

例如,我们可以使用fprintf函数将结果输出到文件中:```matlabfid = fopen('output.txt', 'w');fprintf(fid, 'The value of x is %d\n', x);fclose(fid);```这将在当前目录下创建一个名为output.txt的文件,并将内容输出为"The value of x is 5"。

注意,我们使用%d作为占位符,表示要替换为整数的值。

与fprintf函数类似,sprintf函数用于将格式化文本输出到字符串中,而不是文件。

这在需要将输出结果传递给其他函数或保存到变量中时非常有用。

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

matlab 基本语句1.循环语句forfor i=s1:s3:s2循环语句组end解释:首先给i赋值s1;然后,判断i是否介于s1与s2之间;如果是,则执行循环语句组,i=i+s3(否则,退出循环.);执行完毕后,继续下一次循环。

例:求1到100的和,可以编程如下:sum=0for i=1:1:100sum=sum+iend这个程序也可以用while语句编程。

注:for循环可以通过break语句结束整个for循环.2.循环语句while例:sum=0;i=1;while(i<=100)sum=sum+i;i=i+1;end3.if语句if(条件)语句endif(条件)语句else语句endif(条件)语句elseif语句end4.关系表达式:=,>,<,>=,<=,==(精确等于)5.逻辑表达式:|(或),&(且)6.[n,m]=size(A)(A为矩阵)这样可以得到矩阵A的行和列数n=length(A),可以得到向量A的分量个数;如果是矩阵,则得到矩阵A的行与列数这两个数字中的最大值。

7.!后面接Dos命令可以调用运行一个dos程序。

8.常见函数:poly():为求矩阵的特征多项式的函数,得到的为特征多项式的各个系数。

如a=[1,0,0;0,2,0;0,0,3],则poly(a)=1 -6 11 -6。

相当于poly(a)=1入^3+(-6)入^2+11入+(-6)。

compan():可以求矩阵的伴随矩阵.sin()等三角函数。

MATLAB在数学建模中的应用(3)一、程序设计概述MATLAB所提供的程序设计语言是一种被称为第四代编程语言的高级程序设计语言,其程序简洁,可读性很强,容易调试。

同时,MATLAB的编程效率比C/C++语言要高得多。

MATLAB编程环境有很多。

常用的有:1. 命令窗口2. word窗口3. M-文件编辑器,这是最好的编程环境。

M-文件的扩展名为“.m”。

M-文件的格式分为两种:①l M-脚本文件,也可称为“命令文件”。

②M-函数文件。

这是matlab程序设计的主流。

l保存后的文件可以随时调用。

二、MATLAB程序结构按照现代程序设计的观点,任何算法功能都可以通过三种基本程序结构来实现,这三种结构是:顺序结构、选择结构和循环结构。

其中顺序结构是最基本的结构,它依照语句的自然顺序逐条地执行程序的各条语句。

如果要根据输入数据的实际情况进行逻辑判断,对不同的结果进行不同的处理,可以使用选择结构。

如果需要反复执行某些程序段落,可以使用循环结构。

1 顺序结构顺序结构是由两个程序模块串接构成。

一个程序模块是完成一项独立功能的逻辑单元,它可以是一段程序、一个函数,或者是一条语句。

看图可知,在顺序结构中,这两个程序模块是顺序执行的,即先执行<程序模块1>,然后执行<程序模块2>。

实现顺序结构的方法非常简单,只需将程序语句顺序排列即可。

2 选择结构在MATLAB中,选择结构可由两种语句来实现。

(1)if语句if语句的最简单用法为:if 表达式;程序模块;endif语句的另一种用法为:if 表达式程序模块1else程序模块2end例1 使用if语句判断学生的成绩是否及格。

程序:clearn=input(’输入n= ’)m=60;if n<m,r=’不及格’elser=’及格’end练习一:将例1写入M-文件编辑器,然后在command window 调用这个程序。

当针对多个条件进行选择时,可以采用下面的格式:if 表达式1程序模块1elseif 表达式2程序模块2…………elseif 表达式n程序模块nelse程序模块n+1end例2 将百分之的学生成绩转换为五分制输出。

程序:clearn=input(’输入n= ’)if n>=90chji=’优秀’elseif n>=80chji=’良好’elseif n>=70chji=’中等’elseif n>=60chji=’及格’elsechji=’不及格’end练习二:将例2写入M-文件编辑器,然后在command window 调用这个程序。

(2)switch语句switch语句可以替代多分支的if语句,而且switch语句简洁明了,可读性更好。

其格式为:switch 表达式case 数值1程序模块1case 数值2程序模块2……otherwise程序模块nend其中的otherwise模块可以省略。

switch语句的执行过程是:首先计算表达式的值,然后将其结果与每一个case后面的数值依次进行比较,如果相等,则执行该case的程序模块;如果都不相等,则执行otherwise 模块中的语句。

如图3所示。

例3 用switch…case开关结构将百分制的学生成绩转换为五分制的成绩输出。

程序:clearx=58switch fix(x/10)case {10,9}y=’优秀’case 8y=’良好’case 7y=’中等’case 6y=’及格’otherwisey=’不及格’end练习三:将例3写入M-文件编辑器,然后在command window 调用这个程序。

3 循环结构循环结构的流程图如图4所示它可以多次重复执行某一组语句。

循环是计算机解决问题的主要手段。

在MATLAB中,循环结构可以由两种语句结构实现。

(1)for…end 循环结构。

其格式为:for i=V,循环体结构,end 其中V为一个行向量,循环变量i每次从V中取一个数值,执行一次循环体的内容,如此下去,直到完成V中的所有分量,就自动结束循环体的执行。

例4 计算s=12+22+52。

程序:a=[1 2 5 ]; s=0;for k=a,s=s+k^2;end,s,该例题只是为了说明for语句的格式,事实上,用下面的语句求和更为简单。

命令:p=sum(a.^2)练习四:建立MATLAB与word的连接,在新建的m-book中写入上面的程序,并用notebook 菜单运行之。

循环结构里面还可以包含循环结构,形成多重循环。

例5 设计一个九九乘法表。

程序:clearfor i=1:9for j=1:9a(i , j)=i*j;endenda,练习五:①直接在命令窗编写上面的程序。

②试运行下面的程序,并加以分析:程序:disp(’九九乘法表’),for i=1:9,for j=1:i,p{i}(j)=j*i;end,disp(p{i}),end(2)while…end循环结构。

其格式为:while (表达式)循环结构体end例6 求MATLAB的相对精度解:解题的思路是,让y值不断减小,直到MATLAB分不出1+y与1的差别为止。

程序:y=1; while 1+y>1; y1=y; y=y/2; end,y1说明:①for循环与while循环的区别是,for语句的循环次数是确定的,而while语句的循环次数是不确定的。

②一定要注意在循环结构体内设置“修改条件表达式的语句”,以免进入“死循环”。

③一旦出现死循环,在命令窗用ctrl+c可使程序中止。

④注意程序的可读性。

练习六:在M-文件编辑器内编写上面的脚本文件,并利用菜单或快捷按钮运行之。

三、M-文件M文件是包含MATLAB代码的文件。

M文件按其内容和功能可分为脚本M文件和函数M文件这两大类。

1、脚本M文件脚本M文件是许多MATLAB代码按顺序组成的命令集合,不接受参数的输入和输出,与MATLAB工作区共享变量空间。

脚本文件一般用来实现一个相对独立的功能,比如对某个数据集进行某种分析、绘图,求解方程等等。

前面的几个例题都是脚本文件的类型。

2、函数M文件MATLAB的M-函数是由function语句引导的,其基本格式如下:function [输出形参列表] = 函数名(输入形参列表)注释说明语句段,由%引导;函数体语句函数文件需要在M-文件编辑器中编写。

写完以后,按照当前的搜索路径保存。

以后就可以随时调用这个函数了。

与脚本M文件不同的是,调用函数M文件时需要输入自变量的实际值。

随便打开一个M-文件看一看:open lsqlin编程实例例7. 定义一个函数f(x)=[sin(x)]2, 其中x以“度”为单位。

然后再调用该函数。

解:在M-文件编辑器内写入下面的文件:function y=sinsd(x)%自变量x以“度”为单位。

%%白城师院%数学建模协会,2007-5-12a=x/180*pi;y=sin(a).^2;将上面的文件保存之后即可随时调用。

命令:t=sinsd(45)t =0.5000命令:help sinsd命令:t=sinsd([45,60])t =0.5000 0.7500表明该函数对元素群运算有效。

上面的语句相当于命令:x=[45,60];t=sinsd(x)t =0.5000 0.7500命令:x=[45,60;30,90];f=sinsd(x)f =0.5000 0.75000.2500 1.0000将源文件中最后一行的“.”去掉,再运行以上两条命令,我们会发现什么?例8. 在MATLAB中,一个函数可以调用其它函数,也可以调用自身,即递归调用。

下面利用递归算法编写一个函数,用来计算Fibonacci数列的第k项。

Fibonacci数列:1,1,2,3,5,8,13,21,……M-函数文件:function a=my_fibo(k)if k==1|k==2,a=1;else,a=my_fibo(k-1)+my_fibo(k-2);end将这个文件写入M-文件编辑器并以名称“my_fibo.m”保存,以后就可以调用这个函数。

递归算法无疑是解决某一类问题的有效方法,但不宜滥用,因为它的运算速度往往很慢。

命令:tic, n= my_fibo(26) ,tocn =121393elapsed_time =34.4290下面我们尝试用一般的循环语句来求解这个问题。

程序:tic,n=[1,1];for k=3:100,n(k)=n(k-1)+n(k-2);end,toc,elapsed_time =0.0100命令:n(1:26)ans =Columns 1 through 81 123 58 13 21Columns 9 through 1634 55 89 144 233 377610 987Columns 17 through 241597 2584 4181 6765 1094617711 28657 46368Columns 25 through 2675025 121393例9. 可变输入变量个数的函数MATLAB提供的conv( )函数可用来求两个多项式的乘积。

对于多个多项式的连乘,则不能直接使用此函数,需要用该函数嵌套使用,用起来很不方便。

相关文档
最新文档