资源预览内容
第1页 / 共56页
第2页 / 共56页
第3页 / 共56页
第4页 / 共56页
第5页 / 共56页
第6页 / 共56页
第7页 / 共56页
第8页 / 共56页
第9页 / 共56页
第10页 / 共56页
亲,该文档总共56页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述
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 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 ProgrammingStructured 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 ElementsBasic 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/Output 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 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_code 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 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 increaseIt 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 to 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-file 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 thedifference 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 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 & 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.25Overview 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 need 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 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 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 involving 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: 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 understand 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 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 separated 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:endcreaterowvectorxstartingwithstart,countingbyincrement,endingatorbeforeendlinspace(start,end,number)createrowvectorxstartingwithstart,endingatend,havingnumberelementslength(x)returnsthelengthofvectorxy=xtransposeofvectorx(rowtocolumn,orcolumnntorow)Hands-On DEMO: Creating Vectorsa=1:10%leaveoffsemi-colontoseewhatyougeteachtimeb=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 effective 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.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 print to the command window.MatrixElementsFormat short1.3333 0.0000Format short e1.3333E+000 1.2345E-006Format long1.333333333333338 0.000001234500000Format 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 (*, /, , ) 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 vector.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 matrix 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. (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 arrays (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 and 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=Howaboutthischaracterstring?size(T)ans=132whos%Whatdoyouobserve?NameSizeBytesClassA1x18doublearrayC1x510chararrayD1x1122chararrayT1x3264chararrayans1x216doublearrayGrandtotalis51elementsusing120bytesHands-On DEMO: Strings of Charactersh=Hello;w=World;h,w%calledconcatenationformat Examples(MATLAB performs all computations in double precision)Theformatcommanddescribedbelowswitchesamongdifferentdisplayformats. CommandResultExampleformatshort5digitscaledfixedpoint3.1416formatlong15digitscaledfixedpoint3.14159265358979formatshorte5digitfloating-point3.1416e+00formatlonge15digitfloating-point3.141592653589793e+00formatshortggeneralpurpose5or1.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 : MatLab CalculationsDothefollowinginMatLabCreateamatrixwiththeform:2351Createarow(orhorizontal)vectorof2elements,3and4(inclusive).Createasecondcolumn(orvertical)vectorwiththeelements2and1inthatorder.Typewhostoviewyourvariables.Itshouldread(forexample):whosNameSizeElementsBytesDensityComplexa2by2432FullNob1by2216FullNoc2by1 216FullNoGrandtotalis14elementsusing112bytesHere,aisthematrix,bisthefirstvector,andcisthesecondvector.Nowcompletethefollowingexercise:Multiplyyourmatrixbyyourfirstvector,above.Performelementbyelementdivisionofyourresultingvector,dividedbyyoursecondvectortransposed.(Theresultshouldbeatwoelementhorizontalvectorwith13aseachentry.)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 valuessavefile_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)Create 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 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 workspace (and the command 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 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 initializationomit 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 MyDocumentsusernameRunning 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 . 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!
网站客服QQ:2055934822
金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号