面向数学建模的MATLAB基础EV

上传人:汽*** 文档编号:584023383 上传时间:2024-08-30 格式:PPT 页数:76 大小:1.74MB
返回 下载 相关 举报
面向数学建模的MATLAB基础EV_第1页
第1页 / 共76页
面向数学建模的MATLAB基础EV_第2页
第2页 / 共76页
面向数学建模的MATLAB基础EV_第3页
第3页 / 共76页
面向数学建模的MATLAB基础EV_第4页
第4页 / 共76页
面向数学建模的MATLAB基础EV_第5页
第5页 / 共76页
点击查看更多>>
资源描述

《面向数学建模的MATLAB基础EV》由会员分享,可在线阅读,更多相关《面向数学建模的MATLAB基础EV(76页珍藏版)》请在金锄头文库上搜索。

1、面向数学建模的MATLAB基础MATLABMATLAB环境环境vCommand WindowCommand Window(命令窗口)(命令窗口)vCurrent FolderCurrent Folder(当前工作路径)(当前工作路径)vWorkspace Workspace 和和Command HistoryCommand History2获得系统帮助获得系统帮助vhelphelphelp sinvdocdocdoc eyevlookforlookforlookfor identity3使用使用MATLABMATLAB程序程序v脚本(脚本(Scripts Scripts )按一定顺序排列的可执

2、行命令的集合扩展名为.m不要使用数字作为文件名v在命令行中新建脚本文件在命令行中新建脚本文件edit edit print.mprint.m % %调用调用fprintffprintf函数函数或者点击或者点击 快捷键快捷键ctrl+Nctrl+N 4v在一个脚本中所有被创建和修改的变量会在一个脚本中所有被创建和修改的变量会一直存在于工作区(一直存在于工作区(workspaceworkspace)中,即使)中,即使该脚本已经停止运行该脚本已经停止运行同一命令在脚本中运行与在命令窗口中运行没有本质区别。5简单输出简单输出vdispdisp函数函数输出变量的值、输出字符串例如disp(Hello W

3、orld!);disp(I am going to learn MATLAB!);x = 100;disp(x);6变量类型变量类型v需要创建变量时,可以直接对其赋值,不需要创建变量时,可以直接对其赋值,不用预先定义!用预先定义!v最常用的类型:最常用的类型:double:5.8var1=3.14字符型:a myString=hello world7变量和命名规则变量和命名规则v变量名命名规则:变量名命名规则:第一个字符必须是英文字母由英文字母、数字和下划线构成大小写敏感v内建变量内建变量i和j为虚数单位pi为圆周率ans自动存储最近一次未被保存的运算结果Inf、-Inf分别为正、负无穷8标量

4、标量v定义方法定义方法取名,然后赋值a = 10a = 10c = 1.3*45-2*ac = 1.3*45-2*acool_dudecool_dude = 13/3; = 13/3;注意:分号可以用来抑制输出注意:分号可以用来抑制输出9数组数组v两种类型的数组两种类型的数组矩阵每个元素都是数值(实数或复数)元胞数组元素可以有不同的类型10向量向量v定义向量定义向量行向量row = 1 2 5.4 -6.6row = 1, 2, 5.4, -6.6;列向量column = 4;2;7;411使用使用sizesize和和lengthlength函数函数v计算给定向量的维数计算给定向量的维数siz

5、elength12矩阵矩阵v定义矩阵定义矩阵给出各个元素的值给出各个元素的值M = 1 2 3; 4 5 6M = 1 2 3; 4 5 6;对已有矩阵进行拼接对已有矩阵进行拼接13基本标量运算基本标量运算算术运算算术运算 ( (+, ,-, ,*, ,/) ) 7/457/45(1+i)*(2+i)(1+i)*(2+i)指数运算指数运算()()4242(3+4*j)2(3+4*j)2括号不能隐式地表示乘法运算3(1+0.7) gives an errorTo clear command windowclc14内建函数内建函数vMATLABMATLAB中提供了海量的内建函数中提供了海量的内建函

6、数利用括号进行调用利用括号进行调用sqrt(2)sqrt(2)log(2), log10(0.23)log(2), log10(0.23)cos(1.2), atan(-.8)cos(1.2), atan(-.8)exp(2+4*i)exp(2+4*i)round(1.4), floor(3.3), ceil(4.23)round(1.4), floor(3.3), ceil(4.23)angle(i); abs(1+i);angle(i); abs(1+i);15转置转置v矩阵转置矩阵转置a = 1 2 3 4+ia = 1 2 3 4+itranspose(atranspose(a) )a

7、aa.a.对于实数矩阵来说, . and 运算结果相同,而对于复数矩阵, 还要进行共轭运算。16向量化向量化v逐元素进行运算逐元素进行运算两个运算对象必须维数相同,除非有一个是标量。所有可用于标量的函数也可用于向量t = 1 2 3;f = exp(t);等同于f = exp(1) exp(2) exp(3);17v运算符(* / * / )有两种运算模式逐个元素(element-wise)标准模式18Element-wiseElement-wisevuse the dot: . . (.*.*, ././, .).两运算对象的维数必须相同,除非有一个是标两运算对象的维数必须相同,除非有一个是

8、标量量19标准模式标准模式v标准乘法标准乘法 * * 线性代数规则注意: 矩阵的维数要相匹配!v标准指数运算标准指数运算 只能作用于方阵或标量v左除左除 / and / and 右除右除 右除:相当于乘以运算对象的逆20矩阵的自动初始化矩阵的自动初始化v常用的函数常用的函数onesO = ones(4,5)zerosZ = zeros(6,6)eyeI = eye(7)randR = rand(2,8)元素服从(0,1)均匀分布21向量的生成向量的生成linspacea=linspace(0,10,5)a=linspace(0,10,5)0 0为起点,为起点,1010为终点,共为终点,共5 5

9、个数,等差数列个数,等差数列冒号运算符冒号运算符 : :b=0:2:10b=0:2:100 0为起点,增量为为起点,增量为2 2,不超过,不超过1010增量可以是小数或负数增量可以是小数或负数c=1:5c=1:5默认增量为默认增量为1 122向量元素检索方法向量元素检索方法v向量元素下标从向量元素下标从1 1开始开始a(n)为a中的第n个元素下标参数可以是向量x=12 13 5 8;x=12 13 5 8;a=x(2:3);a=x(2:3);b=x(1:end-1);b=x(1:end-1);a(1)a(2)a(3)a(4)a = 13 5 9 10a=13 5;b=12 13 5;23矩阵元

10、素检索方法矩阵元素检索方法v两种方式两种方式利用元素的行数和列数(行优先)利用元素的编号选取子阵A = rand(5) A(1:3,1:2) A(1 5 3, 1 4) 24冒号通配符冒号通配符选取整行或整列,使用冒号 :25有用的函数有用的函数v求最大值、最小值求最大值、最小值maxminv查找函数查找函数findvec = 5 3 1 9 7;end = find(vec = 9);ind = find(vec 2 & vec Import Data 42符号计算符号计算v告别讨厌的手工演算过程!AdvantagesDisadvantagesSymbolic解析解给出解的直观形式有时不可解

11、解的形式可能相当复杂Numeric总能得到一个解能保证解的精确性易于编程实现对解的深入理解比较困难有时数值方法会失效可能花费较长时间来计算Symbolics vs. Numerics43符号变量符号变量v符号变量同样具有类型(类型为符号)符号变量同样具有类型(类型为符号), , 类似类似 doubledouble或或charcharv使用使用symsym定义符号变量定义符号变量a=sym(1/3);b=sym(4/5);分数不会被求值mat=sym(1 2;3 4);c=sym(c,positive);可以添加标记以缩小取值范围可以添加标记以缩小取值范围see see help sym for

12、 a list of tagsfor a list of tags44v另一种用法另一种用法使用 symssyms x y real等价于 x=sym(x,real); y=sym(y,real);45符号表达式符号表达式v乘法、加法、除法表达式乘法、加法、除法表达式 d=a*b即 1/3*4/5=4/15; expand(a-c)2);展开 factor(ans)因式分解 inv(mat)以符号形式计算逆矩阵46几个函数几个函数 pretty(ans)makes it look nicer collect(3*x+4*y-1/3*x2-x+3/2*y)合并同类项合并同类项 simplify(

13、cos(x)2+sin(x)2)化简化简 subs(c2,c,5)将符号变量替换为数值或表达式将符号变量替换为数值或表达式 subs(c2,c,x/7)ans=25ans=1/49*x247 矩阵可以实现符号运算 mat=sym(a b;c d); mat2=mat*1 3;4 -2;计算乘积 d=det(mat)计算行列式 i=inv(mat)计算逆矩阵 同样的矩阵元素访问方法 i(1,2)48例子例子v已知圆方程已知圆方程求解ysymssyms a b r x y a b r x ysolve(x-a)2+(y-b)2=r2,y)solve(x-a)2+(y-b)2=r2,y)v计算sym

14、ssyms a b x a b xQ=Q=int(xint(x* *exp(x),a,bexp(x),a,b) )subs(Q,a,b,0,2)subs(Q,a,b,0,2)49编写函数编写函数v函数很像脚本函数很像脚本, but for ONE difference, but for ONE difference函数必须有函数声明!OutputsInputsFunction declarationHelp file50If more than one output,User-defined Functions 关于 function declaration的几点说明: No need for

15、 return: MATLAB returns 声明中出现的输出变量声明中出现的输出变量 任何函数内创建的变量仅限于函数内使用,它们不会被返回,任何函数内创建的变量仅限于函数内使用,它们不会被返回,函数运行结束后即消失函数运行结束后即消失function x, y, z = funName(in1, in2)Must have the reserved Function name shouldword: function match MATLAB filenamemust be in bracketsInputs must be specified51例子例子v已知函数声明为已知函数声明为fu

16、nction plotSin(k)v在在0, 20, 2上绘制一个正弦波上绘制一个正弦波sin ( sin ( kxkx ) )v在文件在文件plotSin.mplotSin.m中中, write the , write the following:following:function plotSin(k)x=linspace(0,2*pi,k*20);figureplot(x,sin(k*x)52程序流程控制程序流程控制v关系运算符关系运算符v流程控制语句流程控制语句53 关系运算符关系运算符 MATLAB uses mostly standard relational operatorse

17、qualnot equalgreater thanless thangreater or equalless or equal=short-circuit (scalars)&| Logical operatorsAndOrNotXorAll trueAny trueelementwise&|xorallany Boolean values: zero is false, nonzero is true See help . for a detailed list of operators54if/else/elseif Basic flow-control, common to all la

18、nguages MATLAB syntax is somewhat uniqueIFif condcommandsendELSEif condcommands1elsecommands2endELSEIFif cond1commands1elseif cond2commands2elsecommands3end No need for parentheses: command blocks are betweenreserved wordsConditional statement:evaluates to true or false55for for loops: 主要应用于已知循环次数的情

19、形 MATLAB syntax:for n=1:100commandsend The loop variable被定义为向量在command block中作为标量使用不必为连续整数 The command blockAnything between the for line and the endLoop variableCommand block56while The while is like a more general for loop:主要应用于循环次数未知的情形 The command block will execute while the conditionalexpressi

20、on is true 避免死循环!WHILEwhile condcommandsend57方程组求解方程组求解 考虑求解线性方程组x+2y-3z=5-3x-y+z=-8x-y+z=0 构造矩阵,将方程组改写为 Ax=b A=1 2 -3;-3 -1 1;1 -1 1; b=5;-8;0; And solve with a single line of code! x=Ab;x is a 3x1 vector containing the values of x, y, and z The will work with square or rectangular systems. Gives l

21、east squares(最小二乘) solution for rectangular systems. Solution depends on whether the system is over or underdetermined(超定或欠定).MATLAB makes linearalgebra fun!58More Linear Algebra Given a matrix mat=1 2 -3;-3 -1 1;1 -1 1; Calculate the rank of a matrix r=rank(mat); Calculate the determinant d=det(mat

22、);mat must be squareif determinant is nonzero, matrix is invertible(可逆) Get the matrix inverse E=inv(mat);if an equation is of the form A*x=b with A a square matrix,x=Ab is the same as x=inv(A)*b59Matrix Decompositions MATLAB 提供了常用的矩阵分解方法 The most common ones are V,D=eig(X)Eigenvalue decomposition U

23、,S,V=svd(X)Singular value decomposition Q,R=qr(X)QR decomposition60Exercise: Linear Algebra Solve the following systems of equations:System 1:System 2:x + 4 y = 343x + y = 22 x 2 y = 4 x + y = 33x + 4 y = 261Exercise: Linear Algebra Solve the following systems of equations:System 1:x + 4 y = 343x +

24、y = 2System 2:2 x 2 y = 4 x + y = 33x + 4 y = 2A=1 4;-3 1;b=34;2;rank(A)x=inv(A)*b; A=2 -2;-1 1;3 4; b=4;3;2; rank(A)rectangular matrix x1=Ab;gives least squares solution error=abs(A*x1-b)62 多项式(多项式(Polynomials) 许多函数可以被近似为高阶多项式许多函数可以被近似为高阶多项式 MATLAB 利用系数向量来表示多项式利用系数向量来表示多项式if vector P describes a po

25、lynomialax3+bx2+cx+d P=1 0 -2 represents the polynomial x2-2 P=2 0 0 0 represents the polynomial 2x3P(1)P(2)P(3)P(4)63Polynomial Operations 设设P描述一个描述一个 N阶多项式,显然它是长为阶多项式,显然它是长为N+1的向量的向量 To get the roots of a polynomial r=roots(P)r is a vector of length N Can also get the polynomial from the roots P=p

26、oly(r)r is a vector length N 求给定点的多项式值求给定点的多项式值 y0=polyval(P,x0)x0 is a single value; y0 is a single value To evaluate a polynomial at many points y=polyval(P,x) y=polyval(1 0 1,4 5)x is a vector; y is a vector of the same size y0= polyval(1 0 1, 4)64多项式拟合(多项式拟合(Polynomial Fitting) MATLAB 可以轻松实现给定数据

27、的多项式拟合 Given data vectors X=-1 0 2 and Y=0 -1 3 p2=polyfit(X,Y,2);finds the best second order polynomial that fits the points(-1,0),(0,-1), and (2,3)see help polyfit for more informationplot(X,Y, o, MarkerSize, 10);hold on;x = -3:.01:3;plot(x,polyval(p2,x), r-);65Exercise: Polynomial Fitting x=-4:0.

28、1:4; y=x.2; 给采样点添加随即噪声给采样点添加随即噪声. Use randn. Plot the noisy signal with . markers y=y+randn(size(y); plot(x,y, .); Fit a 2nd degree polynomial to the noisy data p=polyfit(x,y,2); Plot the fitted polynomial on the same plot, using the samex values and a red line hold on; plot(x,polyval(p,x), r) Evalu

29、atefor x=-4:0.1:4.y = x266优化问题优化问题v非线性方程求根非线性方程求根v求函数的最值求函数的最值v优化工具箱优化工具箱67Nonlinear Root Finding 许多实际问题可归结为求解方程许多实际问题可归结为求解方程 f(x)=0 Can use fzero to calculate roots for any arbitrary function fzero needs a function passed to it. Make a separate function file x=fzero(myfun,1) x=fzero(myfun,1)1 spec

30、ifies apoint close to whereyou think the root isCourtesy of The MathWorks, Inc. Used with permission.68Minimizing a Function fminbnd: 在有界区间内寻找最小值点 x=fminbnd(myfun,-1,2);myfun takes a scalar input and returns a scalar outputmyfun(x) will be the minimum of myfun for -1x 2 fminsearch: unconstrained int

31、erval x=fminsearch(myfun,.5)finds the local minimum of myfun near 0.569Anonymous Functions(匿名函数)(匿名函数) 如果函数相当简单,那么不必单独创建文件去定义它 x=fzero(myfun,1)What if myfun is really simple? Instead, you can make an anonymous function x=fzero(x)(cos(exp(x)+x2-1), 1 ); x=fminbnd(x)(cos(exp(x)+x2-1),-1,2);inputfuncti

32、on to evaluate70应用一、用应用一、用linproglinprog()()求解线性规划模型求解线性规划模型 x = linprog(f,A,b,Aeq,beq,LB,UB)目标函数系数约束矩阵右端项解x的上界和下界注意:模型中向量全部为列向量,如果求最大化问题需要转化72线性规划具体的例子线性规划具体的例子v一个线性规划模型归纳为:一个线性规划模型归纳为: f=3 1 3; %转为列向量转为列向量 A=2 1 1;1 2 3;2 2 1; b=2 5 6; LB =zeros(3,1); x = linprog(-f,A,b,LB) z = f*x % 目目标函数函数值73应用二

33、、用应用二、用quadprogquadprog()()求解二次规划模型求解二次规划模型 x = quadprog(H,f,A,b,Aeq,beq,LB,UB)目标函数系数矩阵约束矩阵右端项解x的上界和下界74二次规划具体的例子二次规划具体的例子v一个二次规划模型归纳为:一个二次规划模型归纳为: H = 4 -2 0 0; -2 4 0 0; 0 0 0 0; 0 0 0 0; f = -4;6;0;0; A = ; b =; Aeq = 1 1 1 0;1 5 0 1; beq = 2;5; LB = zeros(size(f); x = QUADPROG(H,f,A,b,Aeq,beq,LB,UB) z = 0.5*x*H*x+f*x75

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 资格认证/考试 > 自考

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号