Intro to Matlab.ppt

上传人:文库蛋蛋多 文档编号:2209907 上传时间:2023-01-31 格式:PPT 页数:56 大小:460.50KB
返回 下载 相关 举报
Intro to Matlab.ppt_第1页
第1页 / 共56页
Intro to Matlab.ppt_第2页
第2页 / 共56页
Intro to Matlab.ppt_第3页
第3页 / 共56页
Intro to Matlab.ppt_第4页
第4页 / 共56页
Intro to Matlab.ppt_第5页
第5页 / 共56页
点击查看更多>>
资源描述

《Intro to Matlab.ppt》由会员分享,可在线阅读,更多相关《Intro to Matlab.ppt(56页珍藏版)》请在三一办公上搜索。

1、WELCOME,EF 105 Fall 2006Week 10,Topics:,Engineering Problem SolvingProgramming LogicIntro to MATLAB,Engineering Problem Solving,Define the problem clearlyWork hand examplesDevelop the Algorithm(Steps to follow)Document the Algorithm with a FLOWCHARTImplement the Algorithm(Write computer program)Test

2、 the Implementation(Run the Program)Evaluate the Results,PROGRAMMING LOGIC:Top-Down Algorithm Development,Divide and ConquerBreak Problem into smaller tasks.Define the interaction between tasks.Recursively solve the individual tasks.Build up the overall solution from the pieces.,Structured Programmi

3、ng,Structured ProgrammingCombination ofSequencesSelectionsLoopsSequencesSeries of operations that are performed in order.SelectionsChoose one path from two or more possible paths.LoopsExecute a block of code repeatedly as long as some condition is met.,Basic Flowcharting Elements,Selection Block,Arr

4、ows show the flow-cannot diverge but can converge.,Exit Point,Execution Block,Input/Output Block,Entry Point,Selection Statements,Selectively choose one path of execution.Based on the evaluation of a test.Logical Test outcome is either TRUE or FALSE.,Loop Structures,Special case of Selection Stateme

5、ntOne branch eventually leads back to the original selection statement.Permits a block of code to be executed repeatedly as long as some test condition is satisfied.,Basic Flowchart Symbols,Practice:Algorithm and Flowchart,Compute a sum of all integers from 1 to 100 and displays the result,Algorithm

6、,Step 4:How do we compute the output?(first solution),Step 4.1:Start with the current integer:1,Step 4.3:Add the current integer to Sum,Step 4.2:Sum starts with 0,Step 4.4:If the current integer is less than 100,keepon adding the current integer to sum and increaseIt by 1(i.e,go back to 4.3).,Step 4

7、.5:Otherwise,print out the sum,Flowchart,Step 4.3:Add the current integer to Sum,Step 4.4:If the current integer is less than 100,go to next integer and keep on adding the current integer to sum(i.e,go back to 4.3).,Step 4.5:Otherwise,print out the sum,Intro to Matlab,Inside MatlabThis is what you s

8、hould see once Matlab has loaded.The three most useful areas in the Matlab window are:1.Right command window is used for inputting commands2.Top left workspace window notes size of matrices used3.Bottom left command history window maintains a sequential list of past commands.,CommandHistory,Workspac

9、e,CommandWindow,CommandHistory,CommandWindow,CommandWindow,Help in MATLAB,The following are three ways to access Matlabs help files:1.a.From options at top of Matlab window select Help Matlab Helpb.Select Index tabc.Type topic to be searched in box2.In Matlab window type a command preceded by help o

10、r doc For example,the following commands would produce a help file for the plot command.help plotordoc plot3.a.Double click command for which you want helpb.Right-click on commandc.Select Help on Selection,Creating files in MATLAB,A.To create a new M-file do one of the following:1.In top left corner

11、 of Matlab window select File New M-file2.Select New M-file shortcut button located at the top left corner of MatlabscreenB.Typing the following clears the command window:clcC.Typing a semicolon at the end of a command suppresses output.Note thedifference between typing the following commands:x=0:0.

12、5:10 x=0:0.5:10;,How/Where to write program,Go to MATLAB command windowFile-New-M-FileM-file is an Editor windowWrite your program in M-fileSave in temp/or your Disk.In command window,Run this file.,+addition-subtraction*multiplication/right division power,Basic Operators,Review Arithmetic Operation

13、s and Precedence,Use Parentheses to Override Operator Precedence,Normal evaluation of expressionsLeft-to-Right if same level and no parentheses,e.g.33-8/4+7-5*2=27-2+7-10=25+7-10=32-10=22,Use parentheses to overridee.g.(33-8)/4+(7-5)*2=(9-8)/4+2*2=1/4+4=4.25,Overview of MatLab Variables,Variables ar

14、e names used to hold values that may change throughout the program.MatLab variables are created when they appear on the left of an equal sign.variable=expression creates the variable and assigns to it the value of the expression on the right hand side.You do not need to define or declare a variable

15、before it is used.x=2%creates a scalar The variable is x and%indicates a comment,Hands-On DEMO:Expression Evaluation,In MatLab,enter the following:x=1.4;numerator=x3-2*x2+x-6.3;denominator=x2+0.05005*x 3.14;f=numerator/denominator,Variable Naming,Naming Rulesmust begin with a letter,cannot contain b

16、lank spacescan contain any combination of letters,numbers and underscore(_)must be unique in the first 31 charactersMatLab is case sensitive:“name”,“Name”and“NAME”are considered different variablesNever use a variable with the same name as a MatLab command(see next slide)Naming convention:Usually us

17、e all_lowercase_letters-or-camelNotation(hump in middle),Reserved Words,MatLab has some special(reserved)words that you may not use as variable names:,Commands involving variables,who:lists the names of defined variableswhos:lists the names and sizes of defined variableswhat:lists all your m-files s

18、tored in memory.clear:clears all variables,reset the default values of special variables.clear name:clears the variable namedclc:clears the command windowclf:clears the current figure and the graph window.,Scalars and Vectors and Matrices,In MatLab,a scalar is a variable with one row and one column.

19、A vector is a matrix with only one row OR only one column.The distinction between row and column vectors is crucial.When working with MatLab you will need to understand how to properly perform linear algebra using scalars,vectors and matrices.MatLab enforces rules on the use of each of these variabl

20、es,Scalars,Scalars are the simple variables that we use and manipulate in simple algebraic equations.To create a scalar you simply introduce it on the left hand side of an equal sign.x=1;y=2;z=x+y;,Vectors,A row vector in MATLAB can be created by an explicit list,starting with a left bracket,enterin

21、g the values separated by spaces(or commas)and closing the vector with a right bracket.A column vector can be created the same way,and the rows are separated by semicolons.Example:x=0 0.25*pi 0.5*pi 0.75*pi pi x=0 0.7854 1.5708 2.3562 3.1416 y=0;0.25*pi;0.5*pi;0.75*pi;pi y=0 0.7854 1.5708 2.3562 3.1

22、416,x is a row vector.y is a column vector.,Simple Vector Commands,Hands-On DEMO:Creating Vectors,a=1:10%leave off semi-colon to see what you get each time b=0:0.1:1 c=7 8 9 d=10;11;12 length(b)linspace(0,100,21),Hands-On DEMO:linspace function,%Plotting a function using vector mathx=linspace(0,20,1

23、00);%define 100 x values(from 0 to 20)y=5*exp(-0.3*x).*sin(x);%compute y vectorplot(x,y),xlabel(X),ylabel(Y),title(Vector calc),linspace()function can be very effective for creating the x vector,A=1 2 3;4 5 6;7 8 9 ORA=1 2 3 4 5 6 7 8 9Must be enclosed in bracketsElements must be separated by commas

24、 or spacesMatrix rows must be separated by semicolons or a returnMatlab is case sensitive,Entering Matrices,x=-1.3 sqrt(3)(1+2+3)*4/5;Output-x=-1.3000 1.7321 4.8000Matrix Manipulation:x(5)=abs(x(1);Let r=1 2 3 4 5;xx=x;r;z=xx(2,2);T=xx(2,1:3);%row 2,col.1-3Semicolon at the end of a line means dont p

25、rint to the command window.,Matrix Elements,Format short1.3333 0.0000Format short e1.3333E+000 1.2345E-006Format long1.333333333333338 0.000001234500000Format long e1.33333333333333E+000 1.234500000000003E-006Format hex3FF555555555555 3EB4B6231ABFD271Defaults to format short.,Output Format,Transpose

26、:A=1 2 3;4 5 6;7 8 9;C=A;D=-1 0 2;,Matrix Operations,The term array operations refer to element-by-element operations.Preceding an operator(*,/,)by a period indicates an element-by-element operation.The addition and subtraction,matrix and array operations are the same and dont need a period before t

27、hese operators.Example:X=1 2 3;Y=4 5 6;W=X.*Y;%to mult.X and Y arrays,Array Operations(using the period),Most often used for a time vector.time=0.0:100.0;Time=10.0:0.5:100.0;B_time=100.0:-0.5:50.0;Variable=first:increment:last,Generating Vectors,Empty MatrixE=;EE(2 4,:)=;Empties rows 2 Creates a 3 x

28、 3 matrix consisting of an identity matrix.(Is on diagonal and 0s elsewhere),Useful Matrices,Hands-On DEMO:Matrix Operations-TransposesTranspose(indicated by)new matrix created by exchanging rows and columns of original matrix,Hands-On DEMO:Functions of Vectors,Most Matlab functions will work equall

29、y well with both scalars and arrays(of any dimension),A=1 2 3 4 5;sin(A)ans=0.8415 0.9093 0.1411-0.7568-0.9589 sqrt(A)ans=1.0000 1.4142 1.7321 2.0000 2.2361,Strings of Characters,MatLab variables may also contain strings,which are vectors of individual characters.There is no typographical difference

30、 in appearance between numerical variables and string variables.The type of variable(numerical or string)is determined when the variable is created.x=5.2%numeric y=Chewbacca%string,What are Character Strings?Arrays!,Example:C=Hello;%C is a 1x5 character array.D=Hello there;%D is a 1x11 character arr

31、ay.A=43;%A is a 1x1 double array.T=How about this character string?size(T)ans=1 32 whos%What do you observe?Name Size Bytes Class A 1x1 8 double array C 1x5 10 char array D 1x11 22 char array T 1x32 64 char array ans 1x2 16 double arrayGrand total is 51 elements using 120 bytes,Hands-On DEMO:Strings

32、 of Characters,h=Hello;w=World;h,w%called concatenation,format Examples(MATLAB performs all computations in double precision),The format command described below switches among different display formats.Command Result Example format short 5 digit scaled fixed point3.1416 format long 15 digit scaled f

33、ixed point 3.14159265358979 format short e 5 digit floating-point3.1416e+00 format long e 15 digit floating-point 3.141592653589793e+00 format short g general purpose 5 or 1.25 or 3.0e-12 format bank Fixed dollars and cents7.95 format rat Ratio of small integers355/113 format compact Suppresses exce

34、ss line feeds.format loose Add line feeds.,Hands-On DEMO:Formatting,p=0:20;format short e%exponentialp pow2(p)pow2(-p)format short g%general purposep pow2(p)pow2(-p),In-Class Exercise:MatLab Calculations,Do the following in MatLabCreate a matrix with the form:2 3 5 1 Create a row(or horizontal)vecto

35、r of 2 elements,3 and 4(inclusive).Create a second column(or vertical)vector with the elements 2 and 1 in that order.Type whos to view your variables.It should read(for example):whos Name Size Elements Bytes Density Complex a 2 by 2 4 32 Full No b 1 by 2 2 16 Full No c 2 by 1 2 16 Full No Grand tota

36、l is 14 elements using 112 bytes Here,a is the matrix,b is the first vector,and c is the second vector.Now complete the following exercise:Multiply your matrix by your first vector,above.Perform element by element division of your resulting vector,divided by your second vector transposed.(The result

37、 should be a two element horizontal vector with 13 as each entry.)Type clear to clear all variables from the workspace.Add your name as%comment,print Command Window and turn in,Saving/Loading Data Values,Be sure you have the correct Current Directory setclear,clcclear workspace and command window to

38、 startassign and calc a few valuessave file_namesaves file_name.mat in current directorysaves all defined variablesclear;load file_namebrings workspace back,Hands-On DEMO:Saving Workspace,First make sure your workspace is clear,and that your Current Directory is set to My Documents subfolder with yo

39、ur username(e.g.Djackson)Create a few scalars and vectorscheck workspace window for variables save demo-OR-click corresponding buttonlook at your folder in My Documents subfolderClear workspace,check Workspace then Reload variables,check Workspace,Scripts,Scripts allow us to group and save MatLab co

40、mmands for future useIf we make an error,we can edit statements and commandsCan modify later to solve other related problemsScript is the MatLab terminology for a programNOTE:Scripts may use variables already defined in the workspace.This can lead to unexpected results.It is a good idea to clear the

41、 workspace(and the command window)at the beginning of all scripts.clear,clc,M-files:Scripts,A Script is the simplest example of an M-file.When a script-file is invoked,MatLab simply executes the commands found in the file.Any variables created in the script are added to the MatLab Workspace.Scripts

42、are particularly useful for automating long sequences of command.,Writing a MATLAB Script(program),File New M-Fileusually start with:clear,clc,format compactcomments after%for in-class exercises include at least:Course,date,section&#(e.g.EF105,Monday 8:00)a short titleyour namesemi-colons to suppres

43、s variable initializationomit semi-colons to display resultsYou can leave off ALL semi-colons to trace a program,Matlab Editor(note Save and Run button),Color keyed text with auto indents,tabbed sheets for other files being edited,Access to commands,Script Files(filename.m),Always check Current Dire

44、ctory WindowSet to MyDocumentsusernameRunning scriptsfrom editor window,click Save and run button-or-just type filename:-or-type run filename,Hands-On DEMO:Creating our First Script(factorial),%fact_n Compute n-factorial,n!=1*2*.*n%by DFJfact=prod(1:n)%no semi-colon so fact displays,File New M-FileF

45、ile Save As.fact_nOperates on a variable in global workspace Variable n must exist in workspaceVariable fact is created(or over-written),Hands-On DEMO:Running your Script,To Run just type n=5;fact_n-OR-n=10;run fact_n,Displaying Code and Getting Help,To list code,use type command type fact_nThe help command displays first consecutive comment lines help fact_n,MATLAB Exercise 1,See the Word document for this exercise and perform at end of class on your own!,

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

当前位置:首页 > 建筑/施工/环境 > 项目建议


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号