MATLAB FUNCTION REVIEWS
MATLAB FUNCTION REVIEWS ENGR1181
Popular in Engineering Fundamentals 1181
Popular in Engineering and Tech
This 23 page Test Prep (MCAT, SAT...) was uploaded by Madison Evans on Monday January 19, 2015. The Test Prep (MCAT, SAT...) belongs to ENGR1181 at Ohio State University taught by Professor Bobby Stephens in Fall. Since its upload, it has received 205 views. For similar materials see Engineering Fundamentals 1181 in Engineering and Tech at Ohio State University.
Reviews for MATLAB FUNCTION REVIEWS
So much better than office hours. Needed something I could understand, and I got it. Will be turning back to StudySoup in the future
-Theresia Hyatt DDS
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 01/19/15
MATLAB FUNCTION REVIEWS CHAPTER 1 Command Window Main window enters variables runs programs mure Window Contains graphic from graphic commands Editor Window Creates and debugs script and function les Help Window Provides help information Type 39help and function in question into command window Command History Window Logs commands entered in the command window Workspace Window Provides information about the variables that are stored Current Folder Window Shows the les in the current folder Several commands can be entered on the same line if separated by a comma When the ENTER is hit the line is executed from left to right Ellipsis When a command is too long it can be continued to the next line by typing three periods and then pressing ENTER Semicolon To suppress any outcome from appearing in the command window add a semicolon after the command in the script window Percent sign Typing at the beginning of a line designates it as a comment and will not appear in the command window The comment is not executed cc command Typing cc and pressing enter clears the command window Command History Window Lists the commands that have been entered in the command window Operation Symbol Example Addition 53 Subtraction 53 Multiplication 53 Right Division 53 Left Division 53 35 Exponential quot 5quot3 53 125 Display Formats The way in which the numbers in the command are formatted COMMAND DESCRIPTION EXAMPLE Format short Fixedpoint with 4 gtgt 2907 decimal digits 414286 short e Format long Fixedpoint with 15 gtgt2907 decimal digits long e 41428571428571 4 Format short e Scienti c notation gtgt2907 with 4 decimal 41429e001 digits Format long e Scienti c notation gtgt 2907 with 5 decimal 414285714 digits e001 Format short g Best of 5digit gtgt 2907 xed or oating 41429 point Format long g Best of 15digit gtgt 2907 xed or oating 414285714 pont Format bank Two decimal digits gtgt 2907 4143 Format compact Eliminates empty lines to allow more lines with information displayed on screen Format loose Adds empty lines opposite of compact FUNCTION DESCRIPTION EXAMPLE sinx Sine in radians gtgt sinpi6 sindx Sine in degrees 05000 cosx Cosine in radians gtgt cosd30 cosdx Cosine in degrees 08660 tanx Tangent in radians gtgt tanpi6 tandx Tangent in degrees 05774 cotx Cotangent in gtgt cotd30 cotdx radians 17321 Cotangent in degrees FUNCTION DESCRIPTION EXAMPLE sqrtx Square root gtgt sqrt81 9 nthrootxn If Xis negative n must be an odd integer Xis the number being rooted n is the root gtgt nthroot805 24022 expx Exponential ex gtgt exp5 1484132 absx Absolute value gtgt abs24 24 ogx NaturaI Iog gtgt og1000 Base e logarithm 69078 In Iog10x Base 10 logarithm gtgt Iog101000 3000 factoriax X gtgt factorial5 X must be 120 positive FUNCTION DESCRIPTION EXAMPLE roundx Round to the gtgt round175 nearest integer 3 xx Round toward zero gtgt x135 2 ceilx Round toward gtgt ceil1l5 in nity 3 oorx Round toward gtgt oor 94 negative in nity 3 remxy Returns the gtgt rem135 remainder after X 3 is divided by y signx Signum function gtgt sign5 Returns 1 if xgt0 1 1 if xlt0 and 0 if x0 A variable is a name of a memory location When a new value is assigned to that variable the old one is replaced Rules About Variable Names Must begin with a letter Can be up to 63 characters long Can contain letters digits and the underscore character Cannot contain punctuation characters period comma semicolon MATLAB is casesensitive AA Aa aA and aa No spaces are allowed between characters use an underscore 0 Avoid using the name of a builtin function for a variable Keywords that appear in blue break case catch cassdef continue ese eseif end for function goba if otherwise parfor persistent return spmd switch try whie pi n infis used for in nity jis the same as i Command Outcome clear Removes all variables from the memory clear x y z Removes only x y 2 variables who Displays a list of current variables whos Displays info about all current variables Script le is also called a program Running the script le is the same as executing it CHAPTER 2 The position of point A can be expressed in terms of position vector rA 2i4j5k i j and kare unit vectors in respect to X y and z A vector is created by assigning the elements of the vector to a variable Creating a vector from known numbers Variablename vector elements Row Vector Create a row vector by typing elements in a bracket separated by a comma or a space Column Vector Create a column vector by typing elements in a bracket separated by a semicolon or pressing enter Spacing variablenamemqn m is the rst element q is the spacing n is the last element Brackets are optional here ex V 2 4 6 8 10 or v2210 rst element 2 spacing 2 last element 10 Equal Spacing variabenamelinspacexixfn xi is rst element xf is last element n is number of elements The spacing between the elements is equal because of the number of elements speci ed When is the number of elements isn t speci ed the spacing is 100 In a square matrix the number of rows is equal to the number of columns m x m In general a matrix is the number of rows by the number of columns m x n m rows n columns A matrix is created by combining column vectors and row vectors Variablename a1 b1 c1 a2 b2 c2 a3 b3 c3 etc ALL OF THE ROWS MUST HAVE THE SAME NUMBER OF ELEMENTS The zeros ones and eye commands zerosmn can be used to create matrices that have elements with special values This command creates a matrix with m rows by n columns where all of the numbers are 0 vzeros410 0000000000 0000000000 0000000000 0000000000 onesmn can be used to create matrices that have elements with special values This command creates a matrix with m rows by n columns where all of the numbers are 1 vones310 l l l l l l l 111 1111111111 1 1 1 1 1 1 1 1 1 1 eyelnl creates a square matrix with n rows and n columns where the diagonal elements are equal to 1 and the rest of the elements are 0 veye3 1 O O O 1 O O O 1 Transposing a vector is adding a apostrophe 39 to the end of a vector Ex gtgt aa 3 8 11 3 8 11 gtgt bbaa 3 8 11 Array addressing is used to pull a speci c element out of a vector or matrix V12345678910 V4 4 The 4th element V8 8 The 8th element Assign a new value to a speci c element in a vector or matrix V8 14 V123456714910 For a matrix to address a speci c element mamn is found m is the row the element is in n is the column the element is in The same can be done with vectors and matrices Using a colon to address an array Vectors Vmn refers to the elements through m and n Matrix An Refers to all elements in all the rows of column n in the matrix An Refers to the elements in all the columns of row n of the matrix Amn Refers to the elements in all the rows in columns m through n Amn Refers to the elements in all the columns in rows m through n Amnpq Refers to the elements in rows m through n and columns p through q Setting a new variable equal to an addressed vector or matrix creates a new vector or matrix Scalar a vector with a single element Vector a matrix with a single row or column Elements can be added to an existing vector by assigning values to the new elements If the vector only has 4 elements in it adding new vectors is done by V14 2 3 4 ltltlt Before vector V58 2 9 5 0 ltltlt Adding more elements 2 3 4 2 9 5 O ltltlt New vector Adding elements to a matrix Adding rows or columns to the matrix by assigning new elements to the matrix If a matrix only has 2 rows selecting the 3rd row and assigning an equal amount of vectors can add a third row Same with the columns Deleting Elements By selecting an element from a matrix or vector then setting it equal to empty brackets eliminates the element FUNCTION DESCRIPTION EXAMPLE lengthA Returns the gtgt A5 9 2 4 number of gtgtlengthA elements in vector 4 A sizeA Returns a row A 6 2 vector mn 5 7 where m and n are gtgtsizeA thesizemxnof 2 5 the vector A reshapeAmn Creates a m and n A 5 1 matrix from the 8 0 elements of matrix A The elements gtgt are taken column BreshapeA32 after column B 5 0 Matrix A must 8 6 have m times n 1 2 elements Strings and strings as variables 0 A string is an array of characters It is created by typing the characters within single quotes 0 Strings can include letters digits other symbols and spaces 0 A string that contains a single quote is created by typing two single quotes within the string 0 The color of the text changes when a string is being typed in 0 When strings are being used in formatting plots labels to axes title and text notes characters within the string can be formatted to have a speci c font size position upper and lowercase color etc When a variable is de ned as a string it stored the same way as numbers are Each character including spaces is an element The elements of the string can be addressed just like elements of a vector or matrix A colon can be used to address a chunk of words gtgt x 365 x 365 gtgt y 39365 The difference here is that x is a number and y is a string that contains 365 digits CHAPTER 3 Element by element operations are used in this section quot A period is added in front of the operation symbol so that the function is applied to every element in the vector separately to a scalar or respectively to another vector When adding subtracting multiplying dividing the dimensions of the vectors or matrices must match AB can only be carried out if the number of columns in A is equal to the number of rows in B The resulting matrix would have the number of rows from A and number of columns from B ABBA Dot product can be found by the function dotab Vectors a and b can be a row vector or column vector Identity Matrix A matrix in which diagonal elements are all ls and the rest of the elements are Os This can be created with the eye command When a vector or matrix is multiplied by an identity matrix the vector or matrix is unchanged because it is like being multiplied by 1 lnverse lf vector b is multiplied by vector a and the product is an identity matrix then b is the inverse of a and a is the inverse of b The inverse of a can be writer as a391 or with the inva function Determinants The product of the elements of a square matrix according to a given rule This function is associated with square matrices detA FUNCTION DESCRIPTION EXAMPLE meanA IfA is a vector gtgt A5 9 2 4 returns the mean gtgtmeanA value of the 5 elements of the vector C maxA IfA is a vector Cis gtgt A 5 8 9 3 4 the largest gtgt CmaxA element A 9 minA The same as gtgt A5 9 3 5 maxA but nds gtgt minA the samellest 3 element sumA IfA is a vector gtgt A5 9 2 4 returns the sum of gtgtsumA the elements of 20 the vector sortA If A is vector gtgt A5 9 2 4 arranges the gtgt sortA vector is ascending 2 4 5 9 order medianA IfA is a vector gtgt A5 9 2 4 returns the median gtgt medianA value of the 45000 elements of the vector Generation of Random Number MATLAB has 3 commands rand randn randi that can be used to assign random numbers to variables Rand command generates uniformily distributed random numbers with values between 0 and 1 This can be used to assign numbers to a scalar vector or matrix rand Randi command generates uniformly distributed random integer Can be used to assign numbers to a scalar vector or matrix randiimaX Where imaX is the max number that the random number can be 1imaX Randn command generates normally distributed numbers with mean 0 and standard deviation of l The command is usually used to generate a single number a vector or matrix in the same way as the rand command randn CHAPTER 4 Input functions are used to type a string or ask the user for a value of a variable Variablename input39What is the value of x 39 Then in the command window the value of X is asked and then used once assigned in the following equations Input command can also be used to assign a string to a variable Variablename input39message to be inputed s Where 395 inside the command de nes the characters that will be entered as a string This is the same as setting the variable equal to a scalar but the variable will be equal to a word or line of characters disp command di5pname of variable gtgt just the value of the variable disp text as string gtgt the text entered in the disp brintfcommand fprintf text typed in as a string This command allows a string and numbers to be displayed together Values can be pulled from certain tables matrices variables and vectors and put into a sentence To start a new line in the middle of the string insert n before the character that will start the new line lnsert n at the end of the string to space the end of the displayed from the next line Fprintf text as string 52f additional text variable shows that a number is inserted in the text 52f is the format of the number f is the conversion character required 5 is how big the number is 2 is the number of digits after the decimal fprintfis vectorized This means that when a variable that is a vector or matrix is included in the command the command is repeated until every element is displayed CHAPTER 5 Plots plotxy where x and y are vectors x and y must have the same number of elements ploty will show a plot of the values of the elements of the vector y1 y2 y3 y4 Plotxy line speci ers PropertyName PropertyValue Only the vectors are mandatory Everything else is optional Line speci ers De ne the size and color of the line and type of markers LineS le S eci er Solid default Dashed n Dotted 39 Dashdot Line Color S eci er Red r Green Blue b C an c Ma enta m Yellow Black White Ex plotxy blue solid line default plotxy r red solid line plotxy y yellow dotted line Property names and Property value Optional and are used to specify thickness of the line size of the marker and colors of the markers edge and ll fplot command fplot39function imits line speci er Where 39function is the function being plotted 39limits are the domains of the x and y axis 39line speci er is how the line being plotted looks plots a function with the form yfx between speci ed limits fx8x25cosx will go into the plot command as 398x25cosx the function cannot contain previous de ned variables unlike the plot command limits are represented as xxminxmax or for example 33 fplot398x25cosx 33 r the limits can also contain the y domain so xminxmaxyminymax Plotting multiple graphs on the same plot There are 3 methods for this 1 Using plot command 2 Using hold on and hold off 3 Using line command Plot command 1 plotxyuvth which creates three graphs y vs x v vs u h vs t all on the same plot vectors must be the same length in each ordered pair line speci ers can be added to this plot function with multiple graphs Hold on and hold off One graph is plotted with the plot command and hold on command is used right after It keeps the gure window open with the rst plot Hold off stops this process Line command Does not need to be known Labelaxes xlabel text as string ylabel text as string Title command title text as string Legend command legend string 1 string 2 string 3 strings are the name of the lines that are graphed in order that they were plotted Plots with logarithmic axes semilogyxy y vs x where y has a log base 10 scale and x has a linear scale semilogxxy y vs x where x has a log base 10 scale and y has a linear scale loglogxy y vs x where both x and y have a log base 10 scale Types of Graphs barxy bar graph VERTICAL barhxy bar graph HORIZONTAL piex pie chart polarthetaradius polar graph subplotmnp l subplot in a subplot graph m by n is split into subplots The upper left subplot is 1 and the bottom right is m by n P is the current subplot that is active CHAPTER 6 Using loops and conditional statements in the program Relational operator Description Lessthan Greater than Less than or equal to Greater than or equal to Equal to Not equal to operation uses 2 equal signs because 1 39 is the assignment operator there are no spaces between ltgt VV 1 When two numbers are compared using these operations if the result is 391 then the expression is true and if the result is 390 then the result is false Only vectorsmatrices of the same size can be compared to result in true or false answers If a scalar is compared to a vector or matrix then the scalar is compared to every element one by one The result would be a vector consisting of Os and ls in respect to the placement of the element being compared Logical vectors this is a vector that is made up of ls and Os from a conditional statement LOGICAL NAME DESCRIPTION OPERATOR 39amp AND Operates on two ex AampB operands A and B If both are true the result is true 1 otherwise the result is false 0 OR Operates on two ex AB operands A and B If either one or both are true the result is true 1 otherwise both are false the result is false 0 NOT Operates on one ex A operand A Gives the opposite of the operand true 1 if the operand is false and false 0 if the operand is true Order of precedence Highest Parentheses ExponenUal Logical NOT MultiplicationDivision AdditionSubtraction Relational operators gtltgtlt Logical AND amp Lowest Logical OR 9 Uquot39gtWquot 39 ndA command nds all of the nonzero elements in vector A ndAgtd command nds all of the elements in vector A that are greater than dscalar anyone operation can be used in the command Conditional Statements Conditional statements commands allow the MATLAB to make a decision on whether to execute or skip a command If the condition is true then the command will be executed but if the command is false then the command will be skipped ifconditional expression consisting of relational andor logical operators The ifstatement is commonly used in three structures ifend ifeseend ifeseif eseend ifend is if the conditional statement with the ifstatement is true 1 then the program will execute the command all the way to the end statement If the conditional statement is false 0 the program will skip the group of commands between ifand end Multiple elseifconditions can be used There must be a conditional statement with it The else statement does not need a conditional statement Every ifneeds an end PI39GE39EdLll39E 1 G n iti n 1 if F r cnaedure 2 Ganditi n 2 eigeif PI UEEdLII E 3 Plquot EEdLllquotE EI Loops A loop is another method to alter the ow of a computer program There are two kinds of loops forend Whileend ln forend loops the number of passes is speci ed at the beginning of the loop ln Whileendloops the number of passes is not known ahead of time and the looping process will continue until the condition statement is satis ed The break command can terminate both loops forend loops The loop index variable can have any variable name usually i j k m and n for k f s t where kis the loop index fis the value of kat the rst pass sis the increment that kchanges in after each pass tis the value of kin the last pass If the increment is omitted then it will automatically be 1 Every for must have an end When the loop ends the loop index variable k has the value that was last assigned to it Whileend loops These loops are used in situations when looping is needed but the number of passes is not known in advance The looping process will continue until the condition is satis ed The rst line in the While loop is a conditional statement and the conditional statement must include one variable The variables must be de ned before the loop starts To get out of an in nite loop press CTRLC Switchcase Command Another method that can be used to direct the ow of a program It can choose one group of commands out of several groups of commands The switch expression can be a scalar or a string The expression can be a mathematical expression that includes preassigned After the switch command there are the cases switch switch expression case value 1 Commands l case value 2 Commands 2 Commands 3 Commands 4 end If there is more than one match then the rst match is executed Otherwise the command otherwise is executed if not cases match up A case statement can have multiple values Case value 1 value 2 value 3 D can be called a cell array CHAPTER 7 FuncUons userde ned function a program created by the user that can be used like a built in function Functions have an input and an output and can be used many times with different input values Function le a separate MATLAB le that contains the code for a userde ned function functionoutputargsUntitledinputargs untitled summary of function detailed explanation end Untitled the name of the function and what the function should be named as the le lnputargs the name of the variables that the function sends back to the user are placed Outputargs names of the variables that the function sends back to the user are placed Ex functionYcacuatedYX YXquot2 end Then when you save the function it can be used the main script ZcalculatedY3 Z9 Functions in a script Imbedded function les directly inside the same script le allows the script le to access a function without saving additional les This reduces issues with sharing and moving les Limitations of functions in script le 1 Only one line functions can be included inside a script le 2 There are two kinds of line functions inline and anonymous lnline Functions An older format Not used that much Anonymous functions Newer format for a function and is more so accepted The general format is Name arglist mathexpression The following is an example of an anonymous function MoflntertiaAhbbhquot312 H3b5 IMoflnertiahb Must has function main at the beginning of the script le which shows that there is going to be an anonymous function There must be an end to the function main Function main script le commans end functionoutputname1input end functionoutputname2input end with function main any in script function can be initialized Nested Functions Same as nested loops A function can be nested inside another funcUon