Lecture 4 - MATLAB Programming - parts 2 and 3
Lecture 4 - MATLAB Programming - parts 2 and 3
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
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