Intro to Matlab - UTK EFD News/Announcements

Download Report

Transcript Intro to Matlab - UTK EFD News/Announcements

WELCOME
EF 105
Fall 2006
Week 12
1
Topics:
1. Program Flows
• More on loops (While)
2
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. The
focus 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 a
specified number of times
• while loops – used to execute a block of instructions while a
certain logical test is true
3
for loopVar = loopVector
Command 1
Command 2
…
Command n
end
The for loop
The for loop is used to execute a block of
statements a specified number of times. It has
the form shown to the right.
Example
Evaluate the following summation:
Sum 
10
3
i

i 1
% filename: for1.m
% Example: Use a for loop to find sum(i^3) for i = 1 to 10.
Sum = 0;
%Initialize variable to zero
for i = 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
for i = [1,2,3,4,5,6,7,8,9,10]
Sum = Sum + i^3;
end
fprintf('Sum = %0.0f\n',Sum);
Results:
>> for1
Sum = 3025
>> for2
Sum = 3025
>>
4
Example
Write a program to determine the balance after N years on an account that contains
an initial deposit D and earns a simple interest of I percent. Prompt the user to
enter values for N, D, and I.
% 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
for years = 1:N
Balance = Balance*(1+I/100);
end
fprintf('Final balance = $%0.2f\n',Balance);
>> 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
5
Nested for loops
For loops can occur within other for loops as shown in the examples below. Note that
while 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
What value for Sum is printed
in the program below?
Sum = 0;
for I = 1:10
for J = 1:15
Sum = Sum + 1;
end
End
fprintf(‘\nSum = %0.0f’,Sum);
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 max6
occurs)
% 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 compact
Rows = input('Enter the number of rows in the matrix: ');
Columns = input('Enter the number of columns in the matrix: ');
for i = 1:Rows
for j = 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;
for i = 1:Rows
for j = 1:Columns
if A(i,j)> Max
Max = A(i,j);
MaxRow = i;
MaxCol = j;
end
end
end
7
fprintf('Max value in array A is A(%0.0f,%0.0f) = %0.2f\n',MaxRow,MaxCol,Max);
>> 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): 14
Enter A(1,3): 17
Enter A(2,1): 23
Enter A(2,2): 11
Enter A(2,3): -8
A =
12
14
17
23
11
-8
Max value in array A is A(2,1) = 23.00
8
The while loop
The while loop is used to execute a
block of statements as long as a
logical test is true. It has the form
shown 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.
9
Another While Example
•Modify the previous program that
calculated the balance in an account after
N years so that it will determine the
number of years to reach a desired
balance.
•See next slide.
10
% 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 account
while Balance < 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
11
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 <= 9
sum = sum + num; num = num + 2;
end
disp(sum)
12
Programming Tips
Use descriptive names. This is true for
script names as well as variable names.
The name need not be long, but it should
relate to the intended use. Short names
such as i, j, k can be used for temporary
variables and loop counters. Remember
not to use blanks or dashes in M-file
names.
13
Other Programming Tips
•Whitespace is essential for making
source files readable.
•Meaningful parts of code are grouped
together by using blank lines as
separators.
•Indentation - use tabs/spaces to indicate
the level of nesting. Don't forget that you
can use the Smart Indent (Text->Smart
Indent) feature of the Matlab text editor to
handle indentation for you.
14
Comments
•Use comments throughout your scripts to explain why
the code is important, not just re-iterate what each
statement is doing.
– Use several lines of comments at the top of each of your
M-Files to describe the script.
– You don't need to comment every statement. Use
comments 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 exist
–mark locations where improvements or enhancements
are planned
15
A Well Documented M File
•Take a look at the baseball trajectory
program.
16
MATLAB Exercise 3
• See the Word document for this
exercise and perform at end of
class on your own!!
17