Publications: 30 | Followers: 0

## EE222_Matlab_Programming_2

Publish on Category: Birds 0

Programming with MATLAB
Puzzle
The following is what seems to be a mathematical proof that two equals one. What's wrong with it?a = baa = abaa - bb = ab - bb(a + b)(a - b) = b(a - b)a + b = ba + a = a2a = a2 = 1
M-files
You can use the command window to enter commands; however, …It is much more efficient to write commands on a text file (M-file), so that you can recall it anytime you want.M-filesare so named because the files are stored with a.mextension.There are two main kinds ofM-filesScript filesFunction files
Script Files
Description:A set of MATLAB commands that are saved on a file.When MATLAB runs a script file, it is as if you typed the characters stored in the file on the command window.ExecutionType their name (without the .m) in the command window,SelectRun(orSave and Run) command in the editing windowHit theF5key while in the editing window.Note that the latter two options will save any edits you have made, while the former will run the file as it exists on the drive.
Script Files - Example
Problem:Develop a script file,FreeFallVelSc, to calculate and plot the velocity of the bungee jumper in the previous example for t = 0-12.Save and run the fileDisplaythe velocity for t = 12 on the command screen.Commands:t = [0:2:20]’;g = 9.81; m = 68.1;cd= 0.25;v =sqrt(g*m/cd)*tanh(sqrt(g*cd/m)*t);plot(t, v)title('Plot of v versus t');xlabel('Values of t');ylabel('Values of v');grid
Function Files
Description:accept input arguments from and return outputs to the command window or a script file.variables created and manipulatedwithinthe function are local.You can call a function several times, changing the input parameters
Function File Syntax
The general syntax for a function is:functionoutvar=funcname(arglist)%helpcommentsstatementsoutvar= value;whereoutvar:output variable namefuncname:function’s namearglist:input argument list - comma-delimited list of what the function calls values passed to ithelpcomments:text to show with helpfuncnamestatements:MATLAB commands for the function
Function Files - Example
Problem:Develop a function file (FreeFallVell)to calculate and plot the velocity of the bungee jumper for t = 0-12, and save this functionSave and run the fileCall the function using the previous parameters.Solution:See page 44Include plotting commandsQuestionWhat change can we make to the function so that the velocity values are displayed on the command line even if a semicolon is used when calling it?
If you include help comments at the beginning of a function file, then typinghelp funcnamewill result in the comments being displayedOnly commented text appearing before any actual command will be displayedType:Help FreeFallVel
Do it Yourself
Problem:Develop a script file that executes FreeFallVelSc for three different sets of parameters and displays the graph on the same plot.
Subfunctions
A function file can contain a single function, but it can also contain aprimary functionand one or moresubfunctionsThe primary function is whatever function is listed first in the M-file - its function name should be the same as the file name.Subfunctionsare listed below the primary function. Note that they areonlyaccessible by the main function andsubfunctionswithin the same M-file andnotby the command window or any other functions or scripts.
Input
Input is used when you would like to get values from the user:forn= input('promptstring')the characters inpromptstringwill be displayedwhatever value is typed is stored inn.For example, if you typepi,nwill store 3.1416…forn= input('promptstring', 's')the characters inpromptstring,whatever characters are typed will be stored as a string inn.For example, if you typepi, the letterspandiwill be stored in a 2x1 char array.
Do it Yourself
Problem:ModifyFreeFallVelScso that it accepts the values of m from the user.Give this new file a different name.Try this for three different values
Output
Thedispcommand is used to display valuesdisp(value)will show thevalueon the screen, and if it is a string, will enclose it in single quotes.ModifyFreeFallVelScso that it displays:The object velocity at time = 12 seconds is:value
Creating and Accessing Files
MATLAB has a built-in file format that may be used to save and load the values in variables.Saving:savefilenamevar1var2...varnsaves the listed variables into a file namedfilename.mat. If no variable is listed, all variables are saved.Loadingload filename var1 var2 ... varnloads the listed variables from a file namedfilename.mat. If no variable is listed, all variables in the file are loaded.Note - these are not text files!
Problem:Save the time, mass and velocity valuesLoad the values
Nice to know
The up arrowWhyHelpControl cSmart indent
Structured Programming
Structured programming allows MATLAB to make decisions or selections based on conditions of the program.Decisions in MATLAB are based on the result of logical and relational operations and are implemented withif,if-else,andif-elseifstructures.Selections in MATLAB are based on comparisons with a test expression and are implemented withswitchstructures.
Relational Operators
From Table 3.2: Summary of relational operators in MATLAB:
Logical Operators
~x(Not): true ifxis false (or zero); false otherwisex & y(And): true if bothxandyare true (or non-zero)x | y(Or): true if eitherxoryare true (or non-zero)
Order of Operations
Priority can be set using parentheses. The order isParenthesesMathematical expressionsrelational operatorslogical operators.All things being equal, expressions are performed from left to right.Logical operators priority order:NotAndOrDo not combine two relational operators!Example: Ifx=5, 3<x<4 should be false (mathematically), but it is calculated as an expression in MATLAB as:3<5<4, which leads totrue<4at which pointtrueis converted to1, and1<4is true!Use(3<x)&(x&lt;4)to properly evaluate the expression.
Decisions
Decisions are made in MATLAB usingifstructures, which may also include severalelseifbranches and possibly a catch-allelsebranch.Deciding which branch runs is based on the result ofconditionswhich are either true or false.If aniftree hits atruecondition, that branch (and that branch only) runs, then the tree terminates.If aniftree gets to anelsestatement without running any prior branch, that branch will run.Note- if theconditionis a matrix, it is considered true if and only if all entries are true (or non-zero).
Decisions Example
Write a script that displays the grade of a student, given his/her percentage score.The rubric is:A = 90-100B = 80-89C = 70-79D = 60-69F = 0-59Also display a comment about the student’s performanceDisplay an error and quit if the score is greater than 100 or less than 0.
Selections
Selections are made in MATLAB using switch structures, which may also include a catch-all otherwise choice.Deciding which branch runs is based on comparing the value in some test expression with values attached to different cases.If the test expression matches the value attached to a case, that case’s branch will run.If no cases match and there is an otherwise statement, that branch will run.
Selections Example
Modify the previous script so that it stores the grade, and then, using case-switch, displays a commentBe creative with your comments.Display an error if the score is greater than 100 or less than 0, but don’t quit.
Loops
With loops, you can run the same lines of code several times and change the parameters.There are two types of loop:A for loop ends after a specified number of repetitions established by the number of columns given to an index variable.A while loop ends on the basis of a logical condition.
forLoops
One common way to use a for…end structure is:forindex=start:step:finishstatementsendwhere theindexvariable takes on successive values in the vector created using the : operator.
Vectorization
Sometimes, it is more efficient to have MATLAB perform calculations on an entire array rather than processing an array element by element. This can be done throughvectorization.
whileLoops
A while loop is fundamentally different from a for loop since while loops can run an indeterminate number of times.The general syntax iswhileconditionstatementsendwhere theconditionis a logical expression. If theconditionis true, thestatementswill run and when that is finished, the loop will again check on thecondition.Note - though theconditionmay become false as thestatementsare running, the only time it matters is after all the statements have run.
Early Termination
Sometimes it will be useful to break out of a for or while loop early - this can be done using a break statement, generally in conjunction with an if structure.Example:x = 24while (1)x = x - 5if x < 0, break, endendwill produce x values of 24, 19, 14, 9, 4, and -1, then stop.
Nice to know
Pause commandCopy the code at the bottom of page 62 to a script, and see what it doesWhite noise generationReading a .wav file in matlab
Anonymous & Inline Functions
Anonymous functionsare simple one-line functions created without the need for anM-filefhandle = @(arg1, arg2, ...) expressionExample:func = @(a,b,c,x,y,z) a*x^3 + b*y^2 + c*z;func(1,2,3,4,5,6);
For-Loops Example