IntrotoMatlab

上传人:cl****1 文档编号:589122076 上传时间:2024-09-10 格式:PPT 页数:56 大小:460.50KB
返回 下载 相关 举报
IntrotoMatlab_第1页
第1页 / 共56页
IntrotoMatlab_第2页
第2页 / 共56页
IntrotoMatlab_第3页
第3页 / 共56页
IntrotoMatlab_第4页
第4页 / 共56页
IntrotoMatlab_第5页
第5页 / 共56页
点击查看更多>>
资源描述

《IntrotoMatlab》由会员分享,可在线阅读,更多相关《IntrotoMatlab(56页珍藏版)》请在金锄头文库上搜索。

1、WELCOMEEF 105 Fall 2006Week 10Topics:1. EngineeringProblemSolving2.ProgrammingLogic3.IntrotoMATLABEngineering Problem SolvingDefine 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 ResultsPROGRAMMING LOGIC:Top-Down Algorithm DevelopmentDivide 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 ProgrammingS

3、tructured ProgrammingStructured 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 ElementsBas

4、ic Flowcharting Elementstest?test?F FT TstartstarttasktaskI/O taskI/O taskstopstopSelection BlockSelection BlockArrows show the flow - cannot diverge but can converge.Arrows show the flow - cannot diverge but can converge.Exit PointExit PointExecution BlockExecution BlockInput/Output BlockInput/Outp

5、ut BlockEntry PointEntry PointSelection StatementsSelection StatementsSelectively choose one path of execution.Based on the evaluation of a test.Logical Test outcome is either TRUE or FALSE.test?test?if_codeif_codeif()if()T TF Ftest?test?if_codeif_code else_codeelse_codeif().elseif().elseF FT TLoop

6、StructuresLoop StructuresSpecialcaseofSelectionStatementOne 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.loop_codloop_code etest?test?F FT Tinc_codeinc_codeini_coini_codedenext_codnext_c

7、ode eBasic Flowchart SymbolsEntryExitTaskI/OQ?TFPractice:AlgorithmandFlowchart Compute a sum of all integers from 1 to 100 and displays the result Step 1: Understand the problem: Computes a sum of all integers from 1 to 100Step 2: What is the input? Step 3: What is the output? Start from 1, stop if

8、reach 100 or (1 and 100)SumAlgorithm Step 4: How do we compute the output? (first solution)Step 4.1: Start with the current integer: 1Step 4.3: Add the current integer to SumStep 4.2: Sum starts with 0Step 4.4: If the current integer is less than 100, keepon adding the current integer to sum and inc

9、reaseIt by 1(i.e, go back to 4.3). Step 4.5:Otherwise, print out the sumFlowchart Step 4.3: Add the current integer to SumStep 4.1: Start with the first integer: 1Step 4.2: Sum starts with 0Step 4.4: If the current integer is less than 100, go to next integer and keep on adding the current integer t

10、o sum (i.e, go back to 4.3).Step 4.5:Otherwise, print out the sumStopCurrent Integer=1Sum=0Sum = Sum +Current IntegerCurrent Integer help plotordoc plot3. a. Double click command for which you want helpb. Right-click on commandc. Select Help on SelectionCreating files in MATLABA. To create a new M-f

11、ile do one of the following:1. In top left corner 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 thed

12、ifference between typing the following commands: x=0:0.5:10 x=0:0.5:10;How/WheretowriteprogramGo 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

13、 division powerBasicOperatorsReview Arithmetic Operations and Precedence OperationAlgebraicMatlab FormScalaradditiona + ba + bsubtractiona ba bmultiplicationa x ba * bdivisiona ba / bexponentiation aba bPrecedenceOperation1Parenthesis, innermost first.2Exponentiation, left to right3Multiplication &

14、division, left to right4Addition & subtraction, left to rightUseParenthesestoOverrideOperatorPrecedenceNormal evaluation of expressionsLeft-to-Right if same level and no parenthesese.g.33-8/4+7-5*2=27-2+7-10=25+7-10=32-10=22Use parentheses to overridee.g.(33-8)/4+(7-5)*2=(9-8)/4+2*2=1/4+4=4.25Overvi

15、ew of MatLab VariablesVariablesare 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 ne

16、ed to define or declare a variable before it is used. x=2 %createsascalarThevariableisx and % indicates a commentHands-On DEMO: Expression EvaluationIn MatLab, enter the following:x=1.4;numerator=x3-2*x2+x-6.3;denominator=x2+0.05005*x3.14;f=numerator/denominatorVariable NamingNaming Rulesmust begin

17、with a letter, cannot contain blank 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

18、next slide)Naming convention:Usually use all_lowercase_letters-or- camelNotation(hump in middle)Reserved WordsMatLab has some special (reserved) words that you may not use as variable names:breakcasecatchcatchcontinueelseelseifendforfunctionglobalifotherwisepersistentreturnswitchtrywhileCommands inv

19、olving variableswho: lists the names of defined variableswhos: lists the names and sizes of defined variableswhat: lists all your m-files stored in memory.clear: clears all variables, reset the default values of special variables.clear name: clears the variable namedclc: clears the command windowclf

20、: clears the current figure and the graph window.Scalars and Vectors and MatricesIn MatLab, a scalar is a variable with one row and one column. A vector is a matrix with only one row OR only one column. Thedistinctionbetweenrowandcolumnvectorsiscrucial. When working with MatLab you will need to unde

21、rstand how to properly perform linear algebra using scalars, vectors and matrices. MatLab enforces rules on the use of each of these variables ScalarsScalars 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

22、 side of an equal sign. x=1;y=2;z=x+y; VectorsA row vector in MATLAB can be created by an explicit list, starting with a left bracket, entering 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 separat

23、ed by semicolons.Example:x=00.25*pi0.5*pi0.75*pipix=00.78541.57082.35623.1416y=0;0.25*pi;0.5*pi;0.75*pi;piy=00.78541.57082.35623.1416x is a row vector.y is a column vector.Simple Vector Commandsx=start:endcreaterowvectorxstartingwithstart,countingbyone,endingatendx=start:increment:endcreaterowvector

24、xstartingwithstart,countingbyincrement,endingatorbeforeendlinspace(start,end,number)createrowvectorxstartingwithstart,endingatend,havingnumberelementslength(x)returnsthelengthofvectorxy=xtransposeofvectorx(rowtocolumn,orcolumnntorow)Hands-On DEMO: Creating Vectorsa=1:10%leaveoffsemi-colontoseewhatyo

25、ugeteachtimeb=0:0.1:1c=789d=10;11;12length(b)linspace(0,100,21)Hands-On DEMO:linspace function%Plottingafunctionusingvectormathx=linspace(0,20,100);%define100xvalues(from0to20)y=5*exp(-0.3*x).*sin(x);%computeyvectorplot(x,y),xlabel(X),ylabel(Y),title(Vectorcalc)linspace() function can be very effect

26、ive for creating the x vectorA = 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 or spacesMatrix rows must be separated by semicolons or a returnMatlab is case sensitiveEntering Matricesx = -1.3 sqrt(3) (1+2+3)*4/5;Output - x = -1.3000 1.73

27、21 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 print to the command window.MatrixElementsFormat short1.3333 0.0000Format short e1.3333E+000 1.2345E-006Format long1.333333333333338 0.00000123

28、4500000Format long e1.33333333333333E+000 1.234500000000003E-006Format hex3FF555555555555 3EB4B6231ABFD271Defaultstoformatshort.OutputFormatTranspose:A = 1 2 3; 4 5 6; 7 8 9;C = A;D = -1 0 2;MatrixOperationsThe term array operations refer to element-by-element operations.Preceding an operator (*, /,

29、 , ) 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 these operators.Example:X = 1 2 3; Y=4 5 6;W = X.*Y; % to mult. X and Y arraysArrayOperations(usingtheperiod)Most often used for a time vect

30、or.time = 0.0:100.0;Time = 10.0:0.5:100.0;B_time = 100.0:-0.5:50.0; Variable = first:increment:lastGeneratingVectorsEmpty MatrixE = ;EE(2 4,:) = ;Empties rows 2 & 4 and all columns in rows 2 & 4.ZerosZe = zeros(2,3);Creates a 2 x 3 matrix consisting all of zeros.OnesO = ones(3,3);Creates a 3 x 3 mat

31、rix consisting all of ones.EyeI = eye(3,3);Creates a 3 x 3 matrix consisting of an identity matrix. (Is on diagonal and 0s elsewhere)UsefulMatricesh=123;h(nothing)ans=123Switches from row to column vector.h*hh.*hans=14ans=149* is matrix multiplication, and so the dimensions must line up correctly. (

32、more on this later).* is entry-by-entry multiplication.Hands-On DEMO: Matrix Operations - TransposesTranspose (indicated by )new matrix created by exchanging rows and columns of original matrixHands-On DEMO: Functions of VectorsMost Matlab functions will work equally well with both scalars and array

33、s (of any dimension)A=12345;sin(A)ans=0.84150.90930.1411-0.7568-0.9589sqrt(A)ans=1.00001.41421.73212.00002.2361Strings of CharactersMatLab variables may also contain strings, which are vectors of individual characters. There is no typographical difference in appearance between numerical variables an

34、d string variables. The type of variable (numerical or string) is determined when the variable is created. x=5.2%numericy=Chewbacca%stringWhat are Character Strings? Arrays!Example:C=Hello;%Cisa1x5characterarray.D=Hellothere;%Disa1x11characterarray.A=43;%Aisa1x1doublearray.T=Howaboutthischaracterstr

35、ing?size(T)ans=132whos%Whatdoyouobserve?NameSizeBytesClassA1x18doublearrayC1x510chararrayD1x1122chararrayT1x3264chararrayans1x216doublearrayGrandtotalis51elementsusing120bytesHands-On DEMO: Strings of Charactersh=Hello;w=World;h,w%calledconcatenationformat Examples(MATLAB performs all computations i

36、n double precision)Theformatcommanddescribedbelowswitchesamongdifferentdisplayformats. CommandResultExampleformatshort5digitscaledfixedpoint3.1416formatlong15digitscaledfixedpoint3.14159265358979formatshorte5digitfloating-point3.1416e+00formatlonge15digitfloating-point3.141592653589793e+00formatshor

37、tggeneralpurpose5or1.25or3.0e-12formatbankFixeddollarsandcents7.95formatratRatioofsmallintegers355/113formatcompactSuppressesexcesslinefeeds.formatlooseAddlinefeeds.Hands-On DEMO: Formattingp=0:20;formatshorte %exponentialppow2(p)pow2(-p)formatshortg%generalpurposeppow2(p)pow2(-p)In-Class Exercise :

38、 MatLab CalculationsDothefollowinginMatLabCreateamatrixwiththeform:2351Createarow(orhorizontal)vectorof2elements,3and4(inclusive).Createasecondcolumn(orvertical)vectorwiththeelements2and1inthatorder.Typewhostoviewyourvariables.Itshouldread(forexample):whosNameSizeElementsBytesDensityComplexa2by2432F

39、ullNob1by2216FullNoc2by1 216FullNoGrandtotalis14elementsusing112bytesHere,aisthematrix,bisthefirstvector,andcisthesecondvector.Nowcompletethefollowingexercise:Multiplyyourmatrixbyyourfirstvector,above.Performelementbyelementdivisionofyourresultingvector,dividedbyyoursecondvectortransposed.(Theresult

40、shouldbeatwoelementhorizontalvectorwith13aseachentry.)Typecleartoclearallvariablesfromtheworkspace.Addyournameas%comment,printCommandWindowandturninSaving/Loading Data ValuesBe sure you have the correct Current Directory setclear, clcclear workspace and command window to startassign and calc a few v

41、aluessavefile_namesaves file_name.mat in current directorysaves all defined variablesclear;loadfile_namebrings workspace backHands-On DEMO: Saving WorkspaceFirst make sure your workspace is clear, and that your Current Directory is set to My Documents subfolder with your username (e.g. Djackson)Crea

42、te a few scalars and vectorscheck workspace window for variablessavedemo-OR- click corresponding buttonlook at your folder in My Documents subfolderClear workspace, check Workspace then Reload variables, check WorkspaceScriptsScripts allow us to group and save MatLab commands for future useIf we mak

43、e 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 workspace (and the comman

44、d window) at the beginning of all scripts.clear, clcM-files: ScriptsA 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 are particularly useful

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

46、alizationomit semi-colons to display resultsYou can leave off ALL semi-colons to trace a programMatlab Editor(note Save and Run button)Color keyed text with auto indentstabbed sheets for other files being editedAccess to commandsScript Files (filename.m)Always check Current Directory WindowSet to My

47、DocumentsusernameRunning scriptsfrom editor window, click Save and run button-or- just type filename: -or- type runfilenameHands-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 displaysFile New M-FileFile Save As .

48、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 ScriptTo Run just typen=5;fact_n -OR- n=10;runfact_nDisplaying Code and Getting HelpTo list code, use type commandtypefact_nThe help command displays first consecutive comment lineshelpfact_nMATLAB Exercise 1SeetheWorddocumentforthisexerciseandperformatendofclassonyourown!

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

最新文档


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

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