while-end loop used when you don't know number of loop iterations you do have a condition that...
TRANSCRIPT
while-end loop used when
• You don't know number of loop iterations
• You do have a condition that you can test and stop looping when it is false. For example,
Keep reading data from a file until you reach the end of the file
Keep adding terms to a sum until the difference of the last two terms is less than a certain amount
while-end Loops
1. Loop evaluatesconditional-expression
2. If conditional-expression is true, executes code in body, then goes back to Step 1
3. If conditional-expression is false, skips code in body and goes to code after end-statement
The conditional expression of a while-end loop
• Has a variable in it
Body of loop must change value of variable
There must be some value of the variable that makes the conditional expression be false
while-end Loops
EXAMPLE
This script
x = 1
while x <= 15
x = 2*x
end
Makes this outputx = 1
x =
2
x =
4
x =
8
x =
16
while-end Loops
The conditional expression of a while-end loop has a variable in it (called the loop variable). The body of the loop must change value of that variable, it is called the update. The update must change the value of the variable in a way that the condition eventually becomes false. It is important, otherwise, you would be stuck in an infinite loop. The loop variable must also be initialized before entering the loop.
while-end Loop
condition body updateinit
INITCONDBODYUPDATE
Remember! If the conditional expression never becomes false, the loop will keep executing... forever!
Your program will just keep running, and if there is no output from the loop (as if often the case), it will look like MATLAB has stopped responding.
If your program gets caught in an indefinite loop, put the cursor in the Command Window and Press CTRL+C.
If the conditional expression never becomes false, the loop will keep executing... forever! It is commonly referred to as an infinite loop. Your program will just keep running, and if there is no output from the loop (as if often the case), it will look like MATLAB has stopped responding.
while-end Loops
1. A sentinel-controlled loop: Sum all the numbers entered by the user until the sentinel is entered (-99).
Basic while-end Loop Examples
sum = 0;n = input ('Enter an integer number (enter -99 to finish input): ');while n ~= -99 sum = sum + n; n = input ('Enter an integer number (enter -99 to finish input): ');endfprintf ('The sum of the numbers is: %d\n', sum);
Enter an integer number (enter -99 to finish input): 4Enter an integer number (enter -99 to finish input): 5Enter an integer number (enter -99 to finish input): 7Enter an integer number (enter -99 to finish input): -99The sum of the numbers is: 16
2. An end-of-file-controlled loop: Sum all the numbers in a file. feof returns true if there are still numbers to be extracted from the file.
Basic while-end Loop Examples
fid = fopen ('data.txt');sum = 0;while ~feof (fid) n = fscanf (fid, '%d'); sum = sum + n;endfprintf ('The sum of the numbers is: %d\n', sum);fclose (fid);
The sum of the numbers is: 166
The sum of all the numbers in the file data.txt.
3. An input validation loop. The enforces that the value entered must be a number between 1 and 5.
Basic while-end Loop Examples
n = input ('Enter an integer number between 1 and 5: ');
while n < 1 | n > 5 n = input ('This is not a number between 1 and 5! Enter again: ');end
fprintf ('Congratulations! You entered: %d\n', n);
Enter an integer number between 1 and 5: 0This is not a number between 1 and 5! Enter again: 7This is not a number between 1 and 5! Enter again: 3Congratulations! You entered: 3
• Common causes of infinite loops:
1. You forgot to change (update) the loop variable value.
distance1 = 1;
distance2 = 10;
distance3 = 0;
while distance1 < distance2
fprintf('Distance = %d\n',distance3);
end
Troubleshooting while-end Loops
Infinite loop!Condition always true!
Common causes of infinite loops:
2. You update the value of the loop variable but in the wrong direction.
distance1 = 1;distance2 = 10;distance3 = 0;while distance1 < distance2
fprintf('Distance = %d\n',distance3); distance1 = distance1 – 1;end
Troubleshooting while-end Loops
Infinite loop!Condition always true!
Should be a + here. Remember that the condition must become false eventually!
Common causes of infinite loops:
3. You update the value of the wrong variable.
distance1 = 1;distance2 = 10;distance3 = 0;while distance1 < distance2
fprintf('Distance = %d\n',distance3); distance3 = distance3 + 1;end
Troubleshooting while-end Loops
Infinite loop again!Both variables in the condition never change values
distance3 is not in the condition
NESTED LOOPS AND NESTED CONDITIONAL STATEMENTSIf a loop or conditional statement is placed inside another loop or conditional statement, the former are said to be nested in the latter.
The most common situation is having an if statement inside a for or a while loop.
Each loop and conditional statement must have an end statement
for k = 1:1:50 if isprime(k) fprintf ('%d ', k); endend
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Common causes of indefinite loops:
• Conditional expression never becomes false
minDistance = 42;
x = 0;
y = 0;
while -sqrt( x^2+y^2 ) < minDistance
x = x + 1;
y = y + x;
end
Typo – shouldn't be any negative sign
while-end Loops
If your program gets caught in an indefinite loop,
• Put the cursor in the Command Window
• Press CTRL+C
T I P
while-end Loops
NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS
If a loop or conditional statement is placed inside another loop or conditional statement, the former are said to be nested in the latter.
• Most common to hear of a nested loop, i.e., a loop within a loop
Often occur when working with two-dimensional problems
• Each loop and conditional statement must have an end statement
NESTED LOOPS AND NESTED CONDITIONAL STATEMENTS
END OF LESSON
Extra readingsFor more knowledge!
• THE break AND continue COMMANDS
The break command:
• When inside a loop (for and while), break terminates execution of loop
MATLAB jumps from break to end command of loop, then continues with next command (does not go back to the for or while command of that loop).
break ends whole loop, not just last pass
• If break inside nested loop, only nested loop terminated (not any outer loops)
• break command in script or function file but not in a loop terminates execution of file
• break command usually used within a conditional statement.
In loops provides way to end looping if some condition is met
• THE break AND continue COMMANDS
Script
while( 1 )
name = input( 'Type name or q to quit: ', 's' );
if length( name ) == 1 && name(1) == 'q'
break;
else
fprintf( 'Your name is %s\n', name );
end
endType name or q to quit: Greg
Your name is Greg
Type name or q to quit: quentin
Your name is quentin
Type name or q to quit: q
>>
Trick – "1" is always true so it makes loop iterate forever!
If user entered only one letter and it is a "q", jump out of loop
Otherwise print name
Only way to exit loop!
• THE break AND continue COMMANDS
The continue command:
Use continue inside a loop (for- and while-) to stop current iteration and start next iteration
continue usually part of a conditional statement. When MATLAB reaches continue it does not execute remaining commands in loop but skips to the end command of loop and then starts a new iteration
• THE break AND continue COMMANDS
for ii=1:100
if rem( ii, 8 ) == 0
count = 0;
fprintf('ii=%d\n',ii);
continue;
end
% code
% more code
end
Every eight iteration reset count to zero, print the iteration number, and skip the remaining computations in the loop
• THE break AND continue COMMANDS
User-Defined Functions and Functions Files
A function is like a command that you create yourself. It can behave like a command already defined in MATLAB.
There are also functions that programmers of the MATLAB organization have created and have placed in MATLAB for us to use. We've seen a number of the "built in" functions up to this point (sqrt, sin, ...), but in this chapter we will be mainly concerned with functions we will write ourselves.
What are functions?
A function is a MATLAB program that can accept inputs and produce outputs. Some functions don't take any inputs and/or produce outputs.
A function is called or executed (run) by another program or function. That program can pass it input and receive the function's output.
Why use functions?
• Use same code in more than one place in program without rewriting code
• Reuse code by calling in different programs
• Make debugging easier by putting all of one kind of functionality in one place
Creating a functionA function is written almost exactly like a script,
except that it starts with the function keyword. Like a script file, it is saved with a .m extension (must use the same file name as your function!). You can make the file in any text editor but it is easiest to do it with the MATLAB Editor/Debugger Window. To create a new function, select the Function item from the New menu.
Code generated automatically by MATLAB
Results (Output values)
Data (Input values)
CREATING A FUNCTION FILE
Code for a function is in an m-file. Can make the file in any text editor but easiest to do it with MATLAB Editor/Debugger Window. To create a new function m-file, select File|New|Function . Window opens that looks like
Can open Editor/Debugger Window with blank file by selecting File|New|Script
Can also open from Command Window by typing edit followed optionally by a filename not in quotes
• If file in current directory, MATLAB opens it
• If not in current directory, MATLAB creates it
CREATING A FUNCTION FILE
A simple function
This is a simple function that converts miles to kilometers.
DATA (INPUT)RESULT
H1 LINE
HELP TEXT
FUNCTION BODY AND ASSIGNMENT OF VALUE TO RESULT VARIABLE
THE FUNCTION DEFINITION LINE
We will explain all the elements in detail in the coming slides.
STRUCTURE OF A FUNCTION FILE
Purpose
• Calculate monthlyand total loanpayments
Inputs
• Amount of loan, interest rate, duration of loan
Outputs
• Monthly and total payments
Function definition line
• Must be first executable line (line not blank or not comment line) in function file
If not, MATLAB considers file to be a script file
• Defines file as function file
• Defines name of function
• Defines number and order of input and output arguments
FUNCTION DEFINITION LINE
Data input parameters (or input arguments as they are sometimes called in MATLAB) are used to transfer data into the function from the calling program.
You can have zero, one or more items of data sent to the function. If there are more than one, you separate the multiple data items with commas inside the parentheses of the function definition line.
Data can be scalars, vectors, or arrays. Their values are specified by the calling program.
Sending Data to Functions
Results (or output arguments as they are sometimes called in MATLAB) are used to transfer data from the function to the calling program.
You can have zero, one or more results from a function. If there are none, you can omit the assignment operator (=). If there is only one, you can omit the brackets. If more than one, you separate them with commas inside the brackets of the function definition line.
Results can be scalars, vectors, or arrays.
Getting Results from Functions
Form of function definition line is
Function name
• Made up of letters, digits, underscores
• Cannot have spaces
• Follows same rules as variable names
Avoid making function names that are same as names of built-in functions
A function name is made up only of letters, digits, and underscores. It cannot have spaces. It follows the same rules as variable names.
Avoid making function names that are same as names of built-in functions.
Function Definition Line
Input arguments
• Used to transfer data into function from calling program
• Can be zero or more input arguments
Separate multiple arguments with commas
• Can be scalars, vectors, or arrays
• Have values specified by calling program
INPUT AND OUTPUT ARGUMENTS
Output arguments
• Used to transfer data out of function to calling program
• Can be zero or more output arguments
In function definition line
If zero arguments, can omit assignment operator (=)
If only one output argument, can omit brackets around it
If multiple arguments, separate them with commas
• Can be scalars, vectors, or arrays
• Have values specified by calling program function
INPUT AND OUTPUT ARGUMENTS
The function definition line must be first executable line (not a blank line nor a comment line) of the function file. If not, MATLAB considers file to be a script file.
It establishes the file as a function file, defines the name of the function, and defines the number and order of input items and results.
Function Definition Line
The H1 Line and Help Text LinesThe H1 line and the help text lines are comment lines (ones that start with a percent sign %). Both types of lines are optional.
They are used to provide the user with information about the function. For example, the user can use the help command to get info about your function from the H1 line.Ex: help miles_to_km
The Simplest Function: No Arguments, No Result
function why%displays 25 question marks on the screen.%Input: none.%Results: none.disp ('?????????????????????????');end
You call (use) the function by simply entering the name of the function in the command window or your script.
>> why?????????????????????????
A Simple Function: One Argument, No Result
The why function only displays the same number of question marks every time.
What if I wanted to display a different number of question marks that could be linked to a numerical value that I send to the function?
All I would need to add is an argument to the function to specify the number of question marks. See why2 on the next slide. why2, like why, has no result.
A Simple Function: One Argument, No Resultfunction why2 (n)
%displays question marks on the screen.%Input: n = number of question marks.%Results: none.for k=1:1:n fprintf ('?');endfprintf ('\n');end
>> why2 (6)??????>> why2 (10)??????????
The H1 Line and Help Text Lines
H1 line and help text lines are comment lines (ones that start with a percent sign (%) )
• Used to provide user with information about function
• Both types of lines are optional
A Simple Function: One Argument, One Result
The miles_to_km function seen earlier is a typical example of that very common type of function of having one input and one result.
Let's have a similar example of converting degrees Fahrenheit into degrees Celcius.
Fahrenheit Celciusfc
A Simple Function: One Argument, One Resultfunction c = fc (f)
%converts c into f.%Input: f = temperature in fahrenheit.%Result: c = temperature in celcius.c = (f - 32) * 5/9;end
>> fc (30)ans = -1.1111>> fc (68)ans = 20
Another Function: One Argument, Two Results
Let's have a similar example of converting degrees Fahrenheit into degrees Celcius but also into degrees Kelvin.
FahrenheitCelcius
f_to_ck Kelvin
Another Function: One Argument, Two Resultsfunction [c,k] = f_to_ck (f)
%converts f into c and k.%Input: f = temperature in fahrenheit.%Results: c = temperature in celcius.% k = temperature in kelvin.c = (f - 32) * 5/9;k = c + 273.15;end
>> [celcius kelvin] = f_to_ck (80)celcius = 26.6667kelvin = 299.8167
Another Function: One Argument, Two ResultsHere a script that uses our f_to_ck function (saved
as degrees.m):far = input ('Enter temperature in degrees Fahrenheit: ');[cel kel] = f_to_ck (far);fprintf ('%.1f degrees Fahrenheit is %.1f degrees Celcius.\n', far, cel);fprintf ('%.1f degrees Fahrenheit is %.1f degrees Kelvin.\n', far, kel);
>> degreesEnter temperature in degrees Fahrenheit: 4545.0 degrees Fahrenheit is 7.2 degrees Celcius.45.0 degrees Fahrenheit is 280.4 degrees Kelvin.
Function: Multiple Arguments, One Result
Let's now have function with three arguments and one result. The formula for a loan repayment is:
M = P * ( J / (1 - (1 + J)^ -(N))) where
M: is the monthly payment.
P: is the principal or amount of the loan
J: is the monthly interest; the annual interest divided by 100, then divided by 12.
N: is the number of months of amortization, determined by length in years of loan.
The three arguments are P, J, and N. The result is M.
Function: Multiple Arguments, One Resultfunction m = loan (p, j, n)
%loan repayment function.%Inputs: p = principal.% j = interest.% n = length of loan in months.%Result: m = monthly payment.j = j / 100 / 12; %compute monthly interestm = p * ( j / (1 - (1 + j)^ (-n))) end
>> format bank>> loan (100000,6,360)ans = 599.55
$100,000 loan6% interest per year30 years
Order of arguments is important!!!
Things to KnowA function usually does not display
anything on the screen (unless the function contains a disp or a fprintf statement).
Variables declared inside a function are unknown in the main program.
Variables of the main program are unknown inside the function (see next slide).
The only way to send values from the main program to a function is through an argument.
Variables inside functions
Variables declared inside a function are local to that function, meaning they can only be used inside that function.
• The calling program can't see (access) any of the variables inside the function.
• The function can't see any variables in the calling program.
Function a = 5 b = ?Input Output
Calling Program a = ? b = 9
a and b from the function are different variables from a and b of the calling program!
Remember!
Variables inside and outside functions can have the same names but are still different variables!
Changing one doesn't change the other!
Scope of Variable Names
function test( n )
fprintf( 'On entering function n = %d\n', n );
n = 10;
fprintf( 'Before leaving function n = %d\n', n );
end
n is still 5 after the function call
Scope of Variable Values - An example
>> n = 5
n = 5
>> test(n)
On entering function n = 5
Before leaving function n = 10
>> n
n = 5
You may see in MATLAB literature mentions of global variables. Variables that have the scope both inside and outside functions.
The use of global variables is not considered good practice. As a result, using global variables on tests/exam or assignments will be considered an error.
LOCAL AND GLOBAL VARIABLES
Anonymous FunctionsAn anonymous function is a function defined without using a separate function file. It is a simple way to define a short one-line function.
They are specified within another function or body of code, not in a separate file. Like the command window or a script file.
Form is:
For example
cube = @(x) x^3
Anonymous Functions
The mathematical expression must contain the variables from the arglist.
>> triple = @(n) 3 * n;>> triple (4)ans = 12>> x = 1.5;>> y = triple(x)y = 4.5000>> km = @(miles) 1.60934 * miles; >> km (50)ans = 80.47>> km (triple (30));ans = 144.84
Anonymous Functions - Examples
Let's create a function named hypotenuse that calculates the longest side of a right-angled triangle given the length of the other two sides (saved as hypotenuse.m). That function uses the anonymous function square that we create as well.
function c = hypotenuse (a, b) %hypotenuse calculation%Inputs: a, b = two shorter sides of the triangle.%Result: c = longest side of the triangle.square = @(x) x^2;c = sqrt (square(a) + square (b)); end
>> hypotenuse (3,4)ans = 5
Anonymous Functions - Example
If want name of MATLAB command that does some particular computation, can search for name by specifying a word or phrase likely to describe that computation. Do this with lookfor command:
lookfor 'word or phrase'
• Put word or phrase inside quote marks
The H1 Line and Help Text Lines
Suppose want to find command that takes square root of a number. A likely word in description of computation is "square"
>> lookfor 'square'
magic - Magic square.
realsqrt - Real square root.
sqrt - Square root.
lscov - Least squares with known covariance.
sqrtm - Matrix square root.
cgs - Conjugate Gradients Squared Method.
and many others. From reading descriptions, can tell command you want is "sqrt"
The H1 Line and Help Text Lines
A likely phrase in description of computation is "square root"
>> lookfor 'square root'
realsqrt - Real square root.
sqrt - Square root.
sqrtm - Matrix square root.
and just a few others
Good news – easy to make lookfor work on functions you write, not just MATLAB functions, by using H1 lines
The H1 Line and Help Text Lines
The H1 line is the first comment line after the function definition line
• Optional
• Only one line long
• Usually contains function name and short definition of function
The H1 Line and Help Text Lines
lookfor 'word' searches in H1 line of all the files that it knows about (including ones you write) for "word". If it finds "word" it prints out file name and H1 line.
When you write an H1 line, put in words that are likely to be used in lookfor
• Good – uses "square" and "root"% mySqrt(x): computes square root of x using Reese algorithm
• Bad – uses "half" and "power"% mySqrt(x): computes x to half power using Reese algorithm
T I P
The H1 Line and Help Text Lines
help command works by displaying H1 line and all following comment lines up to next blank line or code line in function file. Will work on files you write too
To make a blank line appear in help output, use a line with just a percent sign
The H1 Line and Help Text Lines
Function body
• Contains code that does computations
• Code can use
All MATLAB programming features studied before
Special MATLAB commands relevant only to functions