Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Lecture 4 - MATLAB Programming - parts 2 and 3

The lecture covers an introduction to analytical programming using MATLAB, focusing on programming principles, user-defined functions, and data handling. It discusses logical evaluations, control flow statements (if, else, switch), and loops (for, while), along with best practices and common pitfalls in MATLAB programming. The lecture also emphasizes the importance of vectorization for efficient coding in MATLAB.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 4 - MATLAB Programming - parts 2 and 3

The lecture covers an introduction to analytical programming using MATLAB, focusing on programming principles, user-defined functions, and data handling. It discusses logical evaluations, control flow statements (if, else, switch), and loops (for, while), along with best practices and common pitfalls in MATLAB programming. The lecture also emphasizes the importance of vectorization for efficient coding in MATLAB.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 60

ITEC 2600 – Lecture 4:

Introduction to Analytical Programming

Prof. Arik Senderovich


Outline
 MATLAB programming part 1
o Programming principles in MATLAB with examples
o User-defined functions
o Plotting and data load/save
 MATLAB programming part 2:
o Logical evaluation and If statements (elseif, else)
o Switch statement
o is expressions
 MATLAB programming part 3
o For and While loops
o Vectorization
o Additional types of Functions
2
Recall Relational Expressions
• The relational operators in MATLAB are:
> greater than
< less than
>= greater than or equals
<= less than or equals
== equality
~= inequality
• The resulting type is logical 1 for true or 0 for false
• The logical operators are:
|| or for scalars
&& and for scalars
~ not
• Also, xor function which returns logical true if only one of the arguments is true
If Statement
• The if statement is used to determine whether or not a statement
or group of statements is to be executed
• General form:
if condition
action
end
• the condition is any relational expression
• the action is any number of valid statements (including, possibly,
just one)
• if the condition is true, the action is executed – otherwise, it is
skipped entirely
Exchanging values of variables
 Useful, for example, when the value of one variable is supposed to be
less than another – if that is not the case, exchange their values (so, an
if statement is used to determine whether this is necessary or not)
 A temporary variable is necessary
 Algorithm to exchange values of variables a and b:
o Assign the value of a to temp
o Assign the value of b to a
o Assign the value of temp to b
Representing true/false concepts
 Note: to represent the concept of false, 0 is used. To represent
the concept of true, any nonzero value can be used – so
expressions like 5 or ‘x’ result in logical true
 This can lead to some common logical errors
 For example, the following expressions are always true
(because the “relational expressions” on the right, 6 and
‘N’, are nonzero so they are true; therefore, it does not
matter what the results of the others are):
number < 5 || 6
letter == ‘n’ || ‘N’
If-else Statements
• The if-else statement chooses between two actions
• General form:
if condition
action1
else
action2
end
• One and only one action is executed; which one depends on
the value of the condition (action1 if it is logical true or action2
if it is false)
If-else statements are not always necessary!
• Simplify this statement:
if num < 0
num = 0;
else
num = num;
end
• Answer:
if num < 0
num = 0;
end
• The point is that the else clause does not accomplish anything, so it is
not necessary … sometimes just an if statement is all you need!
Throwing an error
 MATLAB has an error function that can be used to display an
error message in red, similar to the error messages generated
by MATLAB
if radius <= 0
error('Sorry; %.2f is not a valid radius\n', radius)
else
% carry on
end
 When an error is thrown in a script, the script stops executing
Nested if-else Statements
• To choose from more than two actions, nested if-else statements can be
used (an if or if-else statement as the action of another)
• General form:
if condition1
action1
else
if condition2
action2
else
if condition3
action3
% etc: there can be many of these
else
actionn % the nth action
end
end
end
The elseif clause
 MATLAB also has an elseif clause which shortens the code (and cuts down
on the number of ends)
 General form:
if condition1
action1
elseif condition2
action2
elseif condition3
action3
% etc: there can be many of these
else
actionn % the nth action
end
The elseif clause is not always necessary!
• Simplify this statement:
if val >= 4
disp('ok')
elseif val < 4
disp('smaller')
end
• Answer:
if val >= 4
disp('ok')
else
disp('smaller')
end
• The point is that if you get to the else clause, you know that
the expression val >= 4 is false – so, val must be less than 4 so
there is no need to check that.
Practice Questions
The switch Statement
• The switch statement can frequently be used in place of a nested if-else
statement
• General form:
switch switch_expression
case caseexp1
action1
case caseexp2
action2
case caseexp3
action3
% etc: there can be many of these
otherwise
actionn
end
• this can be used when comparing the switch_expression to see if it is equal to the values on
the case labels (the otherwise clause handles all other possible values)
The switch Statement - Example
The menu and listdlg functions
• The menu function displays a menu of push-buttons, and
returns the result of the button push (1 for the first button, 2
for the second, etc. – or 0 if no button is pushed)
– Then, a switch or nested if statement is used to perform different
actions based on the menu options
– As of R2015b, this function is no longer recommended
• The listdlg function is similar, and can also be used to present a
menu
The menu Function
The switch Statement - practice
The “is” functions
 There are many “is” functions in MATLAB that
essentially ask a true/false question, and return
logical 1 for true or 0 for false
 isletter returns 1 or 0 for every character in a string –
whether it is a letter of the alphabet or not
 isempty returns 1 if the variable argument is empty,
or 0 if not
 iskeyword returns 1 if the string argument is a
keyword, or 0 if not
 isa determines whether the first argument is a
specified type
Common Pitfalls
 Some common pitfalls have been pointed out
already; others include:
o Using = instead of == for equality in conditions
o Putting a space in the keyword elseif
o Not using quotes when comparing a string variable to
a string, such as
letter == y
instead of
letter == 'y'
o Writing conditions that are more complicated than
necessary, such as
if (x < 5) == 1 instead of just if (x < 5)
Programming Style Guidelines
 Use indentation to show the structure of a script or function.
In particular, the actions in an if statement should be indented.
 When the else clause isn’t needed, use an if statement rather
than an if-else statement
 When using the menu function, ensure that the program
handles the situation when the user clicks on the red ‘X’ on the
menu box rather than pushing one of the buttons.
Outline
 MATLAB programming part 1
o Programming principles in MATLAB with examples
o User-defined functions
o Plotting and data load/save
 MATLAB programming part 2:
o Logical evaluation and If statements (elseif, else)
o Switch statement
o is expressions
 MATLAB programming part 3
o For and While loops
o Vectorization
o Additional types of Functions
23
For loop
 used as a counted loop
 repeats an action a specified number of times
 an iterator or loop variable specifies how many times
to repeat the action
 general form:
for loopvar = range
action
end
 the range is specified by a vector
 the action is repeated for every value of the loop
variable in the specified vector
for loop examples
Loop that uses the iterator variable:
>> for i = 1:3
fprintf('i is %d\n', i)
end
i is 1
i is 2
i is 3

Loop that does not use the iterator variable:


>> for i = 1:3
disp('Howdy')
end
Howdy
Howdy
Howdy
Input in a for loop
 If it is desired to repeat the process of prompting the user and
reading input a specified number of times (N), a for loop is used:
for i = 1:N
% prompt and read in a value
% do something with it!
end
 If it is desired to store the values entered in a vector, the most
efficient method is to preallocate the vector first to have N
elements
Preallocating a Vector

Preallocating sets aside enough memory for a vector to be


stored
The alternative, extending a vector, is very inefficient because
it requires finding new memory and copying values every time
Many functions can be used to preallocate, although it is
common to use zeros
For example, to preallocate a vector vec to have N elements:
vec = zeros(1,N);
for loop uses
• calculate a sum
– initialize running sum variable to zero
• calculate a product
– initialize running product variable to one
• input from user
– can then echo print the input
• sum values in a vector
– can also use built-in function sum for this
• other functions that operate on vectors: prod, cumsum, cumprod,
min, max,cummin, cummax. Let’s implement cumsum for vectors!
For loop application: subplot

 The subplot function creates a matrix (or vector) in


a Figure Window so that multiple plots can be
viewed at once
 If the matrix is m x n, the function call
subplot(m,n,i) refers to element i (which must be
an integer in the range from 1 to m*n)
 The elements in the FW are numbered row-wise
 It is sometimes possible to use a for loop to iterate
through the elements in the Figure Window
Subplot Example
For example, if the subplot matrix is 2 x 2, it may be possible to
loop through the 4 elements to produce the 4 separate plots

Plot 1 Plot 2
Plot 3 Plot 4

for i = 1:4
subplot(2,2,i)
% create plot I (let’s see an example)
end
Nested for loops
• A nested for loop is one inside of ( as the action of) another for loop
• General form of a nested for loop:
for loopvarone = rangeone outer loop
% actionone:
for loopvartwo = rangetwo inner loop
actiontwo
end
end
• The inner loop action is executed in its entirety for every value of the outer loop
variable
Implement the Multiplication Table
For loop – What does this function do?
For loop – What will be printed for each one?
while loop
• used as a conditional loop
• used to repeat an action when ahead of time it is not known how many times the
action will be repeated
• general form:
while condition
action
end
• the action is repeated as long as the condition is true
• an infinite loop can occur if the condition never becomes false (Use Ctrl-C to break
out of an infinite loop)
• Note: since the condition comes before the action, it is possible that the condition
will be false the first time it is evaluated and therefore the action will not be executed
at all
Counting in a while loop
• it is frequently useful to count how many times the action of
the loop has been repeated
• general form of a while loop that counts:
counter = 0;
while condition
% action
counter = counter + 1;
end
% use counter – do something with it!
while loop application: error-checking
• with most user input, there is a valid range of values
• a while loop can be used to keep prompting the user, reading the value, and
checking it, until the user enters a value that is in the correct range
• this is called error-checking
• general form of a while loop that error-checks:
prompt user and input value
while value is not in correct range
print error message
prompt user and input value
end
use value
Example: Prompt for radius
radius = input('Enter the radius of a circle: ');
while radius <= 0
radius = input('Invalid! Enter a positive radius: ');
end
area = pi * radius ^ 2;
fprintf('The area is %.2f\n', area)
While loop practice question
• What is desired is a script “ch5pp” that will prompt the user for a quiz grade and error-check until the
user enters a valid quiz grade. The script will then echo print the grade. For this course, valid grades
are in the range from 0 to 10 in steps of 0.5. Following are examples of executing the script.
• Method: create a vector of valid grades and then do 1 of 3 solutions: using any, all, or find.

>> ch5pp
Valid quiz grades are in the range from 0 to 10 in steps of 0.5
Enter a quiz grade: 4.5
Cool, the grade is 4.5
>> ch5pp
Valid quiz grades are in the range from 0 to 10 in steps of 0.5
Enter a quiz grade: -2
Invalid! Enter a quiz grade: .6
Invalid! Enter a quiz grade: .499
Invalid! Enter a quiz grade: 9.5
Cool, the grade is 9.5
Example Solution I
fprintf('Valid quiz grades are in the range from ')
fprintf('0 to 10 in steps of 0.5\n')
validvec = 0:0.5:10;
quiz = input('Enter a quiz grade: ');
while ~any(quiz==validvec)
quiz = input('Invalid! Enter a quiz grade: ');
end
fprintf('Cool, the grade is %.1f\n', quiz)
Example Solution II
fprintf('Valid quiz grades are in the range from ')
fprintf('0 to 10 in steps of 0.5\n')
validvec = 0:0.5:10;
quiz = input('Enter a quiz grade: ');
while all(quiz~=validvec)
quiz = input('Invalid! Enter a quiz grade: ');
end
fprintf('Cool, the grade is %.1f\n', quiz)
Example Solution III
fprintf('Valid quiz grades are in the range from ')
fprintf('0 to 10 in steps of 0.5\n')
validvec = 0:0.5:10;
quiz = input('Enter a quiz grade: ');
while isempty(find(validvec==quiz))
quiz = input('Invalid! Enter a quiz grade: ');
end
fprintf('Cool, the grade is %.1f\n', quiz)
Error-Checking for Integers
• To error-check for integers, you can input into a variable and then either
round that value or use an integer type function (e.g. int32) to convert
the number that was entered to an integer.
• If the number that was entered originally was an integer, then rounding
or converting will have no effect; the values will be the same
inputnum = input('Enter an integer: ');
num2 = int32(inputnum);
while num2 ~= inputnum
inputnum = input('Invalid! Enter an integer: ');
num2 = int32(inputnum);
end
While Examples
Vectorizing
• The term vectorizing is used in MATLAB for re-writing code
using loops in a traditional programming language to matrix
operations in MATLAB
• For example, instead of looping through all elements in a
vector vec to add 3 to each element, just use scalar addition:

vec = vec + 3;
Efficient Code
 In most cases, code that is faster for the programmer to write
in MATLAB is also faster for MATLAB to execute
 Keep in mind these important features:
o Scalar and array operations
o Logical vectors
o Built-in functions
o Preallocation of vectors
Operations on Vectors & Matrices

• Can perform numerical operations on vectors


and matrices, e.g. vec + 3
• Scalar operations e.g. mat * 3
• Array operators operate term-by-term or
element-by-element, so must be same size
• Addition + and subtraction -
• Array operators for any operation based on
multiplication require dot in front .* ./ .\ .^
Useful Efficient functions
• Keep in mind these useful functions:
– sum, prod, cumsum, cumprod, min, max
– any, all, find
– diff
– “is” functions including isequal
Timing Code (Impact of Vectorization)
• The functions tic and toc are used to time code
– Be careful; other processes running in the background will have an effect so
should run multiple times and average
>> type fortictoc

tic
mysum = 0;
for i = 1:20000000
mysum = mysum + i;
end
toc

>> fortictoc
Elapsed time is 0.090699 seconds.
Vectorization: Example 1
Vectorization: Example 2
Vectorization: Practice
Vectorization: Practice
Vectorization - 1
Vectorization - 1
Vectorization - 2
Common Pitfalls
 Forgetting to initialize a running sum or count
variable to 0 or a running product to 1
 Not realizing that it is possible that the action of
a while loop will never be executed
 Not error-checking input into a program
 Forgetting that subplot numbers the plots
rowwise rather than columnwise.
 Not taking advantage of MATLAB; not
vectorizing!
Programming Style Guidelines
 Use loops for repetition only when necessary
o for statements as counted loops
o while statements as conditional loops
 Do not use i or j for iterator variable names if the use
of the built-in constants i and j is desired.
 Indent the action of loops
 Preallocate vectors and matrices whenever possible
(when the size is known ahead of time).
 If the loop variable is just being used to specify how
many times the action of the loop is to be executed,
use the colon operator 1:n
Gilat Practice Questions

You might also like