Post on 06-Mar-2018
transcript
2009 SpringBIL108E
Function m-files• Functions are subprograms• Function m-files are used to calculate a value of
dependent variable(s) at specified values of independent variable(s)
• Major difference between script and function m-files lies in interaction between m-file and command window. – Script files: able to see all variables stored in memory
and all variables created in script file are stored in memory
– Function files: interacts with command window only through its input and output. Intermediate variables cannot be accessed by command window, unless otherwise specified
2009 SpringBIL108E
Function m-files• Functions use input and output parameters to
communicate with other functions and the commandwindow
• Functions use local variables that exist only while the function is executing. Local variables are distinct fromvariables of the same name in the workspace or in other functions
• Input parameters allow the same calculation procedure (same algorithm) to be applied to different data. Thus, function m-files are reusable
• Functions can call other functions
2009 SpringBIL108E
Syntaxfunction [outArgs] = funName (inArgs)
• outArgs is a comma separated list of variable names• [ ] is optional if there is only one parameter• functions with no outArgs are legal• inArgs is also comma separated list of variable name• functions with no inArgs are legal
2009 SpringBIL108E
Example
Save as addmult.m
Calling “addmult” with no return variables or one return variable causes undesired behavior
2009 SpringBIL108E
Example
Save as addmult.m
Calling “addmult” with no return variables or one return variable causes undesired behavior
2009 SpringBIL108E
Sample ProgramWrite a function called FtoC (FtoC.m) to convert Fahrenheit temperatures into Celsius.
function C = FtoC(F) % Celsius = FtoC(Fahrenheit) % Converts Fahrenheit temperatures to CelsiusC=5*(F-32)/9;
TestFtoC(96)
2009 SpringBIL108E
Summary of Input and Output Parameters
• Values are communicated through input arguments and output arguments
• Variables defined inside a “function” are local to that function. Local variables are invisible to other functions and to the command environment
• The number of return variables should match the number of output variables provided by the function
2009 SpringBIL108E
Text Input and Output• It is usually desirable to print results to the screen or to
a file
• Inputs to functions:• “input” function can be used
• Text output from functions:• “disp” function for simple output• “fprintf” function for formatted output
2009 SpringBIL108E
input
• To this point we have “hard coded” the values of variables into our M-file programs
• The input function allows us to prompt the user to enter a value
• The prompt is displayed in the command window
2009 SpringBIL108E
Input accepts a variety of data:• Scalars• Matrices
– enter inside “square brackets”• Character strings
– enter inside “single quotes”– Or… specify string input with ‘s’
2009 SpringBIL108E
fprintf• “fprintf” gives you more control over your output
than the “disp” function• You can control the exact way in which values are
printed to the screen with the “fprintf” function (fprintf = “file print formatted”)
• The fprintf command is more flexible than the disp command, and allows you to put both variables and text onto the same line
• You can control how many digits to display, and their position
2009 SpringBIL108E
Place holder for your variable value
Variable
8 total spaces2 after the decimal pointfloating point format
You can also use exponential format: %8.2e etc.
2009 SpringBIL108E
fprintf
\n is a carriage return\n insert newline in output string
Also: \t insert tab in output string
2009 SpringBIL108E
Example
• Write a program in an M-file that creates a table of degrees to radians.
• Prompt the user to enter the table starting value, an increment between values, and a final value.
uses the input, disp and fprintf functions
2009 SpringBIL108E
AlgorithmsWhat is an “algorithm”? … a well-defined procedure that allows an agent to
solve a problem. Note: often the agent is a computer or a robot…
Algorithm examples:– Cooking a dish – Shampooing hair– Making a pie
An algorithm must:– Be well-ordered– Each operation must be effectively computable– Terminate
2009 SpringBIL108E
Structures
• Sequence• Selection• Repetition
Sequence Selection Repetition (Loop)
2009 SpringBIL108E
• Selection & repetation structures require comparisons to work
• Comparison is achieved with relational operators– Relational operators are used to test whether two values are
equal, or whether one value is greater than or less than another
– The result of applying a relational operator is a logical value, i.e. the result is either true or false
• Result of a comparison may also be modified by logical operators– Logical operators combine (or negate) logical values to
produce another logical value• There is always more than one way to express the
same comparison
Relational and Logical Operators
2009 SpringBIL108E
• > Greater than• < Less than• == Equal• <= Less than or equal • >= Greater than or equal• ~= Not equal
Note: “=” is the second character. =<, => and =~ are not valid operators.
• ~ Not• & And• | Or
Most computer programs use the number 1 for true and 0 for false
Relational and Logical Operators
2009 SpringBIL108E
Example
>> a =2 ; b = 4;>> aIsSmaller = a < b >> bIsSmaller = b < a
aIsSmaller = bIsSmaller =1 0
These operations can be performed on matrices of same shape>> x = 1: 5; y = 5 : -1: 1;>> z = x>y
z = 0 0 0 1 1
2009 SpringBIL108E
Example>> x = [1 2 3 4 5];>> y = [-2 0 2 4 6];>> z = [8 8 8 8 8];>> z>x & z>y
ans =1 1 1 1 1
>> x>y | x>zans =
1 1 1 0 0
2009 SpringBIL108E
Flowcharting• As you write more complicated programs, it becomes
more and more important to plan your code before you write it– Flowcharts – graphical approach– Pseudo-code – verbal description
2009 SpringBIL108E
Flowcharting• Flowcharting is a technique used in designing and
representing algorithms• Create a big picture graphically
– Flowchart is a graph consisting of geometric shapesconnected by flow lines
• From flowchart one can write the program code– Convert to pseudo-code first
2009 SpringBIL108E
Symbols
or• Terminal symbol: an oval (or
circle) indicates the beginning of a section of code
• Process symbol: Calculations and processes are placed in rectangles
• Input-Output symbol: aparallelogram indicates an input or output
• Decision symbol: a diamond indicates a decision point
2009 SpringBIL108E
Symbols
“Flow Lines” indicating the logical sequence of statements.
One must follow the flow of thearrows direction, one cannot goin the opposite direction of thearrows flow.
2009 SpringBIL108E
Example• You’ve been asked to create a program to
convert miles/hr to ft/s. The output should be a table.
• Outline the steps– Define a vector of mph values– Convert mph to ft/s– Combine the mph and ft/s vectors into a matrix– Display the table
2009 SpringBIL108E
Start
Define a vector of miles/hour
Calculate the ft/sec vector
Combine into a table
Create an output table using disp
and fprintf
Flow Chart for Algorithm
End
2009 SpringBIL108E
Washing Machine Instructions• Separate clothes into white clothes and colored
clothes• For white clothes:
– Set water temperature knob to HOT– Place white laundry in tub
• For colored clothes:– Set water temperature knob to COLD– Place colored laundry in tub
• Add 1 cup of powdered laundry detergent to tub• Close lid and press the start button
2009 SpringBIL108E
Start
Separate Clothes into Light / Darkand Select which one to wash
YES NOSet Temp. to HOT
Are Cloths White?
Set Temp. to COLD
Place Cloths in Tub
Add 1 cup detergent to Tub
Close Lid and Press Start Button
Stop
Flow Chart for Algorithm
2009 SpringBIL108E
Conditional Execution -Selection• As the result of a comparison or another logical
(true/false) test, selected blocks of program code are executed or skipped.
• Conditional execution is implemented with if, if...else, and if...elseif constructs, or with a switch construct.
• There are three types of “if” constructs1. if2. if...else3. if...elseif
2009 SpringBIL108E
if Constructs• Syntax:
if expressionblock of statements
end
• The block of statements is executed only if the expression is true.
• Example:if a < 0
disp('a is negative');end
2009 SpringBIL108E
if• One line format uses comma after “if” expression
if a < 0, disp('a is negative'); end• Easy to interpret for scalars• What does an “if” construct mean if the comparison
includes a matrix?– The comparison is only true if it is true for every
member of the array
2009 SpringBIL108E
if...else Constructs• The simple “if” triggers the execution of a block of
code if a condition is true• If it is false that block of code is skipped, and the
program continues without doing anything• What if instead you want to execute an alternate set
of code if the condition is false?
Block of code to execute if the
comparison is true
ComparisonTrue False
Block of code to execute if the
comparison is false
2009 SpringBIL108E
if...else• Example:
if x < 0disp(' x is negative; sqrt(x) is imaginary ');
elser = sqrt(x);
end
2009 SpringBIL108E
if/else/elseif Construct• Use the elseif for multiple selection criteria• It’s a good idea to include a default “else” to catch
cases that don’t match preceding “if” and “elseif” blocks
if x > 0disp('x is positive');
elseif x < 0disp('x is negative');
elsedisp('x is exactly zero');
end
2009 SpringBIL108E
Start
if age<16True
Sorry –You’ll have to wait
age<18You may have a youth license
age<70
True
You may have a standard license
True
Drivers over 70 require a special license
End
elseif
elseif
else
Write a program to determine if an applicant is eligible to drive
2009 SpringBIL108E
switch/case Constructs• This structure is an alternative to the if/else/elseif
structure• The code is generally easier to read• This structure allows you to choose between multiple
outcomes, based on some criterion, which must be exactly true
• When to use?– The criterion can be either a scalar (a number) or a
string. – In practice, it is used more with strings than with
numbers.
2009 SpringBIL108E
• Syntax:switch expression
case value1,block of statements
case value2,block of statements
...otherwise,
block of statementsend
switch/case Constructs
2009 SpringBIL108E
Repetition Structures - Loops• Loops are used when you need to repeat a set of
instructions multiple times • A sequence of calculations is repeated until either
– All elements in a vector or matrix have been processed
– The calculations have produced a result that meets a predetermined termination criterion
• MATLAB supports two types of loops– for– while
2009 SpringBIL108E
for• “for” loops are most often used when each element in
a vector or matrix is to be processed• loop is executed once for each element of the index
matrix identified in the first line
• Syntax:for index = expression
block of statementsend
Check to see if the index has been exceeded
Calculations
Y
N
2009 SpringBIL108E
• Example: Sum of elements in a vectorx = 1:5; % create a row vectorsumx = 0; % initialize the sumfor k = 1:length(x)
sumx = sumx + x(k);end
• Example: A loop with an index incremented by twofor k = 1:2:n
...end
• Example: A loop with an index that counts downfor k = n:-1:1
...end
2009 SpringBIL108E
Nested Loops
• Loop and branch statements can also be nested
• % Nested loops for i=1:4
for j=1:3 disp([i j i*j])
end end
2009 SpringBIL108E
while• while loops are most often used when an iteration is
repeated until some termination criterion is met.
• Syntax:while expression
block of statementsend
• The block of statements is executed as long as expression is true.
Check to see if the criterion is still true
CalculationsY
N
2009 SpringBIL108E
Example
We have to increment the counter every time through the loop – or the loop will never stop!!
This loop creates the matrix a, one element at a time
Start the counter
2009 SpringBIL108E
• The “break” and “return” statements provide an alternative way to exit from a loop construct.
• They may be applied to “for” or “while” loops.• Both are used in conjunction with an “if” statement.
break & return
2009 SpringBIL108E
continue• “break” causes the loop to terminate prematurely
Stop execution of the remainder of the program • “continue” is similar to “break”
However instead of terminating the loop, the program just skips to the next pass through the loopContinue on until the criteria for ending is met
2009 SpringBIL108E
Hints• Be sure to suppress intermediate calculations when
you use a loop • Printing those values to the screen will greatly
increase the amount of execution time• Don’t forget that you can exit the calculation
manually with “ctrl c”
2009 SpringBIL108E
Hints• In general, using a for loop (or a while loop) is less
efficient in MATLAB than using array operations• Vectorization of MATLAB code allows it to execute
much more efficiently, and therefore more quickly • Loops in particular should be avoided in MATLAB,
although this is not always possible
2009 SpringBIL108E
Data Analysis Functions• max(x) Determines the largest value in x• min(x) Determines the smallest value in x• sum(x) Determines the sum of the elements in x• prod(x) Determines the product of the elements in x• sort (x) Returns a vector with the values of x in
ascending order
2009 SpringBIL108E
Mean and Median• mean(x) Computes the mean (average value)
of the elements of the vector x.• median(x) Determines the median value of the
elements in the vector x
N
N
kk
N
kk
xxxxwhere
N
x
.......211
1
2009 SpringBIL108E
Variance and Standard Deviation• By simply, the variance of
the values from the mean
• The standard deviation is defined as the square root of the variance
1
)(1
2
2
N
xN
kk
• var(x) Computes the variance of values in x• std(x) Computes the standard deviation of values in x
2009 SpringBIL108E
The function sin(x) can be written as a Taylor series by
0
12
)!12()1(sin
k
kk
kxx
Write a user-defined function file that calculates sin(x) by usingTaylor’s series. For the function name and arguments usey=Tsin(x,n). The input arguments are the angle x in degrees, andn the number of terms in the series. Use the function to calculatesin(150°) using 3 and 7 terms.
EXAMPLE 1: