the week of 12
TRANSCRIPT
-
8/10/2019 The week of 12
1/17
1
WELCOMEEF 105
Fall 2006
Week 12
-
8/10/2019 The week of 12
2/17
2
Topics:
1. Program Flows
More on loops (While)
-
8/10/2019 The week of 12
3/17
3
MATLAB program Structures
Control Structures
In the last lecture three types of control structures were
described: Straight line control
Conditional control (or branching structures)
Iterative control (or looping structures)
Conditional structures were covered in the last lecture. Thefocus of this lecture will be iterative structures.
Iterative Structures
MATLAB offers two types of iterative structures: for loops primarily used to execute a block of statements aspecified number of times
while loops used to execute a block of instructions while acertain logical test is true
-
8/10/2019 The week of 12
4/17
4
The forloop
The for loop is used to execute a block ofstatements a specified number of times. It has
the form shown to the right.
for loopVar = loopVector
Command 1
Command 2
Command n
endExample
Evaluate the following summation:
10
1i
3iSum
>> for1
Sum = 3025
>> for2Sum = 3025
>>
% filename: for1.m% Example: Use a for loop to find sum(i^3) for i = 1 to 10.
Sum = 0; %Initialize variable to zero
fori = 1:1:10
Sum = Sum + i^3;
end
fprintf('Sum = %0.0f\n',Sum);
% filename: for2.m
% Example: Use a for loop to find sum(i^3) for i = 1 to 10.
Sum = 0; %Initialize variable to zero
fori = [1,2,3,4,5,6,7,8,9,10]
Sum = Sum + i^3;
end
fprintf('Sum = %0.0f\n',Sum);
Results:
-
8/10/2019 The week of 12
5/17
5
Example
Write a program to determine the balance after N years on an account that containsan initial deposit D and earns a simple interest of I percent. Prompt the user to
enter values for N, D, and I.
>> Interest
Enter the amount of the initial deposit: $1000
Enter the percent interest rate: 6
Enter the number of years: 10
Final balance = $1790.85
% Sample program to determine the final balance in a savings account where
% D = initial deposit
% I = interest rate (percent)
% N = number of years
% Filename: Interest.m
D = input('Enter the amount of the initial deposit: $');
I = input('Enter the percent interest rate: ');N = input('Enter the number of years: ');
Balance = D; %Initial value in the account
foryears = 1:N
Balance = Balance*(1+I/100);
end
fprintf('Final balance = $%0.2f\n',Balance);
-
8/10/2019 The week of 12
6/17
6
Nested forloops
For loops can occur within other for loops as shown in the examples below. Note thatwhile indenting loops is not required, it helps to make them more readable.
for loopVar1 = loopVector1
Command 1
for loopVar2 = loopVector2
Command A1
Command A2
Command An
end
Command 2
Command n
end
Sum = 0;for I = 1:10
for J = 1:15
Sum = Sum + 1;
end
End
fprintf(\nSum = %0.0f,Sum);
What value for Sum is printedin the program below?
Example:
The example program on the following slide:
Prompts the user to enter each value of a 2D array
Calculates the maximum value of the array (and the row/column where the maxoccurs)
-
8/10/2019 The week of 12
7/17
7
% Program to prompt the user to enter values in a matrix
% by row and column number.
% Also find the max value in the matrix.
% Filename: Matrixmax.m
format compactRows = input('Enter the number of rows in the matrix: ');
Columns = input('Enter the number of columns in the matrix: ');
fori = 1:Rows
forj = 1:Columns
fprintf('Enter A(%0.0f,%0.0f):',i,j);
A(i,j) = input(' ');
end
end
A
% find the max value in the matrix
Max = A(1,1); %Set max to first value in array
MaxRow = 1;
MaxCol = 1;
fori = 1:Rows
forj = 1:ColumnsifA(i,j)> Max
Max = A(i,j);
MaxRow = i;
MaxCol = j;
end
end
end
fprintf('Max value in array A is A(%0.0f,%0.0f) = %0.2f\n',MaxRow,MaxCol,Max);
-
8/10/2019 The week of 12
8/17
8
>> Matrixmax
Enter the number of rows in the matrix:
2
Enter the number of columns in the
matrix: 3
Enter A(1,1): 12
Enter A(1,2): 14Enter A(1,3): 17
Enter A(2,1): 23
Enter A(2,2): 11
Enter A(2,3): -8A =
12 14 17
23 11 -8
Max value in array A is A(2,1) = 23.00
-
8/10/2019 The week of 12
9/17
9
The whileloop
The while loop is used to execute a
block of statements as long as alogical test is true. It has the formshown to the right.
while LogicalTest
Command 1
Command 2
Command n
end
TRY IT: What is the greatest value of n that can be used in
the sum 12 + 22+ + n2 and get a value of less than 100?>> S = 1; n = 1;
>> while S+ (n+1)^2 < 100; n = n+1; S = S + n^2;
end
>> [n, S]
ans = 6 91
The lines of code between while and end will only be
executed if the condition S+ (n+1)^2 < 100 is true.
-
8/10/2019 The week of 12
10/17
10
Another While Example
Modify the previous program thatcalculated the balance in an account after
N years so that it will determine the
number of years to reach a desiredbalance.
See next slide.
-
8/10/2019 The week of 12
11/17
11
% Sample program to determine the number of years required for an initial
% balance to reach a final value
% Deposit = initial deposit
% Desired_Balance = final value to be reached
% I = interest rate (percent)
% N = number of years
% Filename: Interest2.m
Deposit = input('Enter the amount of the initial deposit: $');
Desired_Balance = input('Enter the desired final balance: $');
I = input('Enter the percent interest rate: ');
N = 0; %Initialize the number of years
Balance = Deposit; %Initial value in the accountwhileBalance < Desired_Balance
N = N+1;
Balance = Balance*(1+I/100);
end
fprintf('\nResults:\nFinal balance = $%0.2f\n',Balance);
fprintf('Number of years to reach final balance = %0.0f\n',N);
>> Interest2
Enter the amount of the initial deposit: $1000
Enter the desired final balance: $3000
Enter the percent interest rate: 7
Results:
Final balance = $3158.82
Number of years to reach final balance = 17
-
8/10/2019 The week of 12
12/17
12
While Example2
Suppose we wish to sum the odd integers
from 1 to 9 using a while loop. Here is the
Matlab code to do that:
sum = 0; num = 1;
while num
-
8/10/2019 The week of 12
13/17
13
Programming Tips
Use descriptive names.This is true forscript names as well as variable names.The name need not be long, but it should
relate to the intended use. Short namessuch as i,j, kcan be used for temporaryvariables and loop counters. Remembernot to use blanks or dashes in M-file
names.
-
8/10/2019 The week of 12
14/17
14
Other Programming Tips
Whitespace is essential for makingsource files readable.
Meaningful parts of code are grouped
together by using blank lines asseparators.
Indentation - use tabs/spaces to indicatethe level of nesting. Don't forget that you
can use the Smart Indent (Text->SmartIndent) feature of the Matlab text editor tohandle indentation for you.
-
8/10/2019 The week of 12
15/17
15
CommentsUse commentsthroughout your scripts to explain why
the code is important, not just re-iterate what eachstatement is doing.
Use several lines of comments at the top of each of yourM-Files to describe the script.
You don't need to comment every statement. Usecomments to:
highlight the major steps of your algorithm
explain long calculations or conditions
clarify convoluted or unusual code
mark locations where you suspect a bug may existmark locations where improvements or enhancementsare planned
-
8/10/2019 The week of 12
16/17
16
A Well Documented M FileTake a look at the baseball trajectory
program.
-
8/10/2019 The week of 12
17/17
17
MATLAB Exercise 3
See the Word document for this
exercise and perform at end of
class on your own!!