面向数学建模的MATLAB基础REV.ppt

上传人:本田雅阁 文档编号:3210566 上传时间:2019-07-31 格式:PPT 页数:76 大小:1.74MB
返回 下载 相关 举报
面向数学建模的MATLAB基础REV.ppt_第1页
第1页 / 共76页
面向数学建模的MATLAB基础REV.ppt_第2页
第2页 / 共76页
面向数学建模的MATLAB基础REV.ppt_第3页
第3页 / 共76页
面向数学建模的MATLAB基础REV.ppt_第4页
第4页 / 共76页
面向数学建模的MATLAB基础REV.ppt_第5页
第5页 / 共76页
点击查看更多>>
资源描述

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

1、面向数学建模的MATLAB基础,2,MATLAB环境,Command Window(命令窗口) Current Folder(当前工作路径) Workspace 和Command History,3,获得系统帮助,help help sin doc doc eye lookfor lookfor identity,4,使用MATLAB程序,脚本(Scripts ) 按一定顺序排列的可执行命令的集合 扩展名为.m 不要使用数字作为文件名 在命令行中新建脚本文件 edit print.m %调用fprintf函数 或者点击 快捷键ctrl+N,5,在一个脚本中所有被创建和修改的变量会一直存在于工作

2、区(workspace)中,即使该脚本已经停止运行 同一命令在脚本中运行与在命令窗口中运行没有本质区别。,6,简单输出,disp函数 输出变量的值、输出字符串 例如 disp(Hello World!); disp(I am going to learn MATLAB!); x = 100; disp(x);,7,变量类型,需要创建变量时,可以直接对其赋值,不用预先定义! 最常用的类型: double: 5.8 var1=3.14 字符型: a myString=hello world,8,变量和命名规则,变量名命名规则: 第一个字符必须是英文字母 由英文字母、数字和下划线构成 大小写敏感 内

3、建变量 i和j为虚数单位 pi为圆周率 ans自动存储最近一次未被保存的运算结果 Inf、-Inf分别为正、负无穷,9,标量,定义方法 取名,然后赋值 a = 10 c = 1.3*45-2*a cool_dude = 13/3; 注意:分号可以用来抑制输出,10,数组,两种类型的数组 矩阵 每个元素都是数值(实数或复数) 元胞数组 元素可以有不同的类型,11,向量,定义向量 行向量 row = 1 2 5.4 -6.6 row = 1, 2, 5.4, -6.6; 列向量 column = 4;2;7;4,12,使用size和length函数,计算给定向量的维数 size length,13

4、,矩阵,定义矩阵 给出各个元素的值 M = 1 2 3; 4 5 6; 对已有矩阵进行拼接,14,基本标量运算,算术运算 (+,-,*,/) 7/45 (1+i)*(2+i) 指数运算() 42 (3+4*j)2 括号不能隐式地表示乘法运算 3(1+0.7) gives an error To clear command window clc,15,内建函数,MATLAB中提供了海量的内建函数 利用括号进行调用 sqrt(2) log(2), log10(0.23) cos(1.2), atan(-.8) exp(2+4*i) round(1.4), floor(3.3), ceil(4.23

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

6、). 两运算对象的维数必须相同,除非有一个是标量,20,标准模式,标准乘法 * 线性代数规则 注意: 矩阵的维数要相匹配! 标准指数运算 只能作用于方阵或标量 左除 / and 右除 右除:相当于乘以运算对象的逆,21,矩阵的自动初始化,常用的函数 ones O = ones(4,5) zeros Z = zeros(6,6) eye I = eye(7) rand R = rand(2,8) 元素服从(0,1)均匀分布,22,向量的生成,linspace a=linspace(0,10,5) 0为起点,10为终点,共5个数,等差数列 冒号运算符 : b=0:2:10 0为起点,增量为2,不超

7、过10 增量可以是小数或负数 c=1:5 默认增量为1,23,向量元素检索方法,向量元素下标从1开始 a(n)为a中的第n个元素 下标参数可以是向量 x=12 13 5 8; a=x(2:3); b=x(1:end-1);,a(1),a(2),a(3),a(4),a = 13 5 9 10,a=13 5; b=12 13 5;,24,矩阵元素检索方法,两种方式 利用元素的行数和列数(行优先) 利用元素的编号 选取子阵 A = rand(5) A(1:3,1:2) A(1 5 3, 1 4),25,冒号通配符,选取整行或整列,使用冒号 :,26,有用的函数,求最大值、最小值 max min 查找

8、函数 find vec = 5 3 1 9 7; end = find(vec = 9); ind = find(vec 2 ,27,绘图功能,已知n个点,可使用plot函数绘制曲线,各点之间用直线连接 x=linspace(0,4*pi,10); y=sin(x); plot(x,y); x=linspace(0,4*pi,1000); plot(x,sin(x);,28,Plot参数选项,可以通过字符串参数指定线条颜色,marker风格和线条风格 plot(x,y,k.-); Look at help plot for a full list of colors, markers, and

9、 linestyles,color,marker,line-style,29,三维和其他绘图方式,其它绘图函数 plot3 surf 见peaks mesh ezplot ezplot3,30,高级数据结构,前面学习了二维矩阵 可以扩展到n维 每个元素的类型必须相同(如整型,字符型) 存储高效、计算方便 含有许多零的大矩阵可被转化为稀疏矩阵 a=zeros(100); a(1,3)=10; a(21,5)=pi; b=sparse(a);,31,元胞数组和结构体,在某些情况下,使用更复杂的数据结构更加方便 Cell array: 与数组类似,但元素可以具有不同类型 Structs: 可以将变量

10、名和变量值绑定在一起,32,Cells: organization 元胞非常类似矩阵,但其每个field可以容纳任何东西(甚至其它矩阵):, 一个元胞可以包含:人名,年龄和他的孩子的年龄。,33,Cells: initialization 可以通过指定 size来自动初始化一个元胞 a=cell(3,10); a will be a cell with 3 rows and 10 columns 或者使用花括号进行手动初始化 c= hello world, 1 5 6 2, rand(3,2) ; c is a cell with 1 row and 3 columns Each elemen

11、t of a cell can be anything, 使用花括号来访问元胞中的元素 ,a1,1=1 3 4 -10; a2,1=hello world 2; a1,2=c3;,34,Structs,Structs 允许我们命名一些变量并将其绑在一起 要初始化一个空的struct: s=struct(); 初始化不是必须的 增加fields: s.name = Jack Bauer; s.scores = 95 98 67; s.year = G3; Fields can be anything: matrix, cell, even struct For more information,

12、 see doc struct,35,工作区变量的保存、读入和清除,save 可将工作区中的部分或全部变量保存到文件中 save myfile x y save myfile load load myfile clear 清除部分或全部变量 clear x y clear all,36,数据输入输出,MATLAB提供了一些接口函数,可以方便的通过文件进行数据输入输出 dlmwrite 可以把数据写为.txt格式的数据,并且数和数之间的间隔符号可以自己定义,如空格,逗号等等。 dlmread 读取.txt格式的文件。 xlswrite 把数据直接写到一个excel文件中。 xlsread 可以从

13、excel文件中读数据。,37,dlmwrite和dlmread,将矩阵M存入文件myfile.txt中,数据分隔符为tab,精度为6位有效数字: dlmwrite(myfile.txt, M, delimiter, t, . precision, 6) 0.893898 0.284409 0.582792 0.432907 0.199138 0.469224 0.423496 0.22595 0.298723 0.0647811 0.515512 0.579807 0.661443 0.988335 0.333951 0.760365 从文件myfile.txt中读取数据,并存入M M =

14、dlmread(myfile.txt) 函数用法详见help文档,38,importdata函数,设文本文件textFile.txt中含有数据: 利用importdata来导入数据 a=importdata(textFile.txt); a 是结构体,包括data, textdata, 和colheaders x=a.data; names=a.colheaders,39,importdata函数,使用importdata时, 可以指定分隔符 a=importdata(filename, , ); 指定逗号为分隔符 如果需要更灵活的读取数据,可以使用 fscanf (similar to C/

15、Java), textread textscan. See help or doc for information on how to use these functions,40,写入Excel Files,xlswrite函数 xlswrite(randomNumbers,rand(10,4),. Sheet1); Sheet1为指定的表单名称 如果有一堆混合类型的数据,可以将其构成元胞数组再写入文件 C=hello,goodbye;10,-2;-3,4; xlswrite(randomNumbers,C, . mixedData);,41,读取Excel Files,xlsread函数

16、num,txt,raw=xlsread(randomNumbers.xls); 读取第一个表单 num中为数字, txt中为字符串, raw包括整个元胞数组的内容 num,txt,raw=xlsread(randomNumbers.xls,. mixedData); Reads the mixedData sheet num,txt,raw=xlsread(randomNumbers.xls,-1); Opens the file in an Excel window and lets you click on the data you want!,42,导入数据最容易的方式是使用Import

17、 Wizard 一个图形用户接口 Import Wizard 允许直接控制要创建的变量 导入向导的位置 File Import Data,43,符号计算,告别讨厌的手工演算过程!,Symbolics vs. Numerics,44,符号变量,符号变量同样具有类型(类型为符号), 类似 double或char 使用sym定义符号变量 a=sym(1/3); b=sym(4/5); 分数不会被求值 mat=sym(1 2;3 4); c=sym(c,positive); 可以添加标记以缩小取值范围 see help sym for a list of tags,45,另一种用法 使用 syms s

18、yms x y real 等价于 x=sym(x,real); y=sym(y,real);,46,符号表达式,乘法、加法、除法表达式, d=a*b,即 1/3*4/5=4/15;, expand(a-c)2);,展开, factor(ans),因式分解, inv(mat),以符号形式计算逆矩阵,47,几个函数, pretty(ans) makes it look nicer collect(3*x+4*y-1/3*x2-x+3/2*y) 合并同类项 simplify(cos(x)2+sin(x)2) 化简, subs(c2,c,5) 将符号变量替换为数值或表达式, subs(c2,c,x/7

19、),ans= 25,ans= 1/49*x2,48, 矩阵可以实现符号运算, mat=sym(a b;c d);, mat2=mat*1 3;4 -2;,计算乘积, d=det(mat),计算行列式, i=inv(mat),计算逆矩阵, 同样的矩阵元素访问方法, i(1,2),49,例子,已知圆方程 求解y syms a b r x y solve(x-a)2+(y-b)2=r2,y) 计算 syms a b x Q=int(x*exp(x),a,b) subs(Q,a,b,0,2),50,编写函数,函数很像脚本, but for ONE difference 函数必须有函数声明!,Outpu

20、ts,Inputs,Function declaration,Help file,51,If more than one output,User-defined Functions, 关于 function declaration的几点说明:, No need for return: MATLAB returns 声明中出现的输出变量, 任何函数内创建的变量仅限于函数内使用,它们不会被返回,函数运行结束后即消失,function x, y, z = funName(in1, in2),Must have the reserved Function name should word: funct

21、ion match MATLAB file,name,must be in brackets,Inputs must be specified,52,例子,已知函数声明为 function plotSin(k) 在0, 2上绘制一个正弦波sin ( kx ) 在文件plotSin.m中, write the following: function plotSin(k) x=linspace(0,2*pi,k*20); figure plot(x,sin(k*x),53,程序流程控制,关系运算符 流程控制语句,54,关系运算符 MATLAB uses mostly standard relati

22、onal operators,equal not equal greater than less than greater or equal less or equal,= = = =,short-circuit (scalars) & |, Logical operators And Or Not Xor All true Any true,elementwise & | xor all any, Boolean values: zero is false, nonzero is true See help . for a detailed list of operators,55,if/e

23、lse/elseif Basic flow-control, common to all languages MATLAB syntax is somewhat unique,IF,if cond,commands,end,ELSE,if cond,commands1,else,commands2,end,ELSEIF,if cond1,commands1,elseif cond2,commands2,else commands3,end No need for parentheses: command blocks are between reserved words,Conditional

24、 statement: evaluates to true or false,56,for for loops: 主要应用于已知循环次数的情形, MATLAB syntax:,for n=1:100 commands,end, The loop variable 被定义为向量 在command block中作为标量使用 不必为连续整数 The command block Anything between the for line and the end,Loop variable,Command block,57,while, The while is like a more general

25、for loop:,主要应用于循环次数未知的情形, The command block will execute while the conditional,expression is true, 避免死循环!,WHILE,while cond commands,end,58,方程组求解, 考虑求解线性方程组 x+2y-3z=5,-3x-y+z=-8 x-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

26、containing the values of x, y, and z The will work with square or rectangular systems. Gives least squares(最小二乘) solution for rectangular systems. Solution depends on whether the system is over or underdetermined(超定或欠定).,MATLAB makes linear algebra fun!,59,More Linear Algebra, Given a matrix, mat=1

27、2 -3;-3 -1 1;1 -1 1;, Calculate the rank of a matrix, r=rank(mat);, Calculate the determinant, d=det(mat);,mat must be square,if 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

28、(A)*b,60,Matrix Decompositions, MATLAB 提供了常用的矩阵分解方法, The most common ones are, V,D=eig(X),Eigenvalue decomposition, U,S,V=svd(X),Singular value decomposition, Q,R=qr(X) QR decomposition,61,Exercise: Linear Algebra, Solve the following systems of equations:,System 1:,System 2:,x + 4 y = 34 3x + y = 2

29、,2 x 2 y = 4, x + y = 3 3x + 4 y = 2,62,Exercise: Linear Algebra Solve the following systems of equations:,System 1: x + 4 y = 34 3x + y = 2,System 2: 2 x 2 y = 4 x + y = 3 3x + 4 y = 2, ,A=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

30、 squares solution error=abs(A*x1-b),63,多项式(Polynomials) 许多函数可以被近似为高阶多项式 MATLAB 利用系数向量来表示多项式 if vector P describes a polynomial ax3+bx2+cx+d, P=1 0 -2 represents the polynomial x2-2 P=2 0 0 0 represents the polynomial 2x3,P(1),P(2),P(3),P(4),64,Polynomial Operations, 设P描述一个 N阶多项式,显然它是长为N+1的向量 To get

31、the roots of a polynomial, r=roots(P),r is a vector of length N, Can also get the polynomial from the roots, P=poly(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 v

32、ector; y is a vector of the same size, y0= polyval(1 0 1, 4),65,多项式拟合(Polynomial Fitting) MATLAB 可以轻松实现给定数据的多项式拟合 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 information, ,p

33、lot(X,Y, o, MarkerSize, 10); hold on; x = -3:.01:3; plot(x,polyval(p2,x), r-);,66,Exercise: Polynomial Fitting, x=-4:0.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 fit

34、ted polynomial on the same plot, using the same x values and a red line hold on; plot(x,polyval(p,x), r), Evaluate,for x=-4:0.1:4.,y = x2,67,优化问题,非线性方程求根 求函数的最值 优化工具箱,68,Nonlinear Root Finding, 许多实际问题可归结为求解方程 f(x)=0 Can use fzero to calculate roots for any arbitrary function, fzero needs a function

35、passed to it., Make a separate function file, x=fzero(myfun,1) x=fzero(myfun,1),1 specifies a,point close to where you think the root is,Courtesy of The MathWorks, Inc. Used with permission.,69,Minimizing a Function, fminbnd: 在有界区间内寻找最小值点, x=fminbnd(myfun,-1,2);,myfun takes a scalar input and return

36、s a scalar output,myfun(x) will be the minimum of myfun for -1x 2, fminsearch: unconstrained interval, x=fminsearch(myfun,.5),finds the local minimum of myfun near 0.5,70,Anonymous Functions(匿名函数) 如果函数相当简单,那么不必单独创建文件去定义它 x=fzero(myfun,1) What if myfun is really simple? Instead, you can make an anony

37、mous function x=fzero(x)(cos(exp(x)+x2-1), 1 );, x=fminbnd(x)(cos(exp(x)+x2-1),-1,2);,input,function to evaluate,71,Optimization Toolbox, If you are familiar with optimization methods, use the,optimization toolbox, Useful for larger, more structured optimization problems, Sample functions (see help

38、for more info), linprog,linear programming using interior point methods, quadprog,quadratic programming solver, graphshortestpath,solves the shortest path problem in graph,72,应用一、用linprog()求解线性规划模型,x = linprog(f,A,b,Aeq,beq,LB,UB),目标函数系数,约束矩阵,右端项,解x的上界和下界,注意:模型中向量全部为列向量,如果求最大化问题需要转化,73,线性规划具体的例子,一个线

39、性规划模型归纳为:, 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 % 目标函数值,74,应用二、用quadprog()求解二次规划模型,x = quadprog(H,f,A,b,Aeq,beq,LB,UB),目标函数系数矩阵,约束矩阵,右端项,解x的上界和下界,75,二次规划具体的例子,一个二次规划模型归纳为:, 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*x,Thank You !,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 其他


经营许可证编号:宁ICP备18001539号-1