Ch 3: MATLAB Programming

PGE 310: Formulation and Solution in Geosystems Engineering
Dr. Balhoff
Spring 2011
MATLAB Programming
Chapter 3
of
Numerical Methods with MATLAB, Gerald Recktenwald
1
Review of Plotting in MATLAB
•
Matlab has some really powerful graphics
3
10
1
0.8
2D plots can be made easily in MATLAB
plot(x,y)
Annotating helps make a professional plot
subplot(x,y,thisplot) command allows for multiple plots
Log plots also common
0.4
0.2
2
10
0
-0.2
-0.4
-0.6
-0.8
1
10
•
Linear Plot
–
–
–
–
0.6
Semilog Plot
•
0
100
200
300
400
500
600
700
0
0.5
800
-1
900
1
1.5
3D plots (surface and contour) are also useful
–
–
–
–
surf(x,y,Z)-or surfc, surfl, mesh- uses vectors
surf(X,Y,Z) uses matrices for X and Y
contour(X,Y,Z)
‘meshgrid(x,y)’ converts vector data of x, y to matrices
0.5
0
-0.5
2
0
-2
-2
-1.5
-1
-0.5
2
2
1
Today…We learn some real programming!
•
Script files and function-files
– Two types of ‘.m’ files
– Code written in MATLAB
•
function files require inputs and send back outputs
– We have already been using functions!
– Any number of inputs and outputs allowed
•
Input and Output (1/O)
– input
– disp
– fprintf
3
Scripts: Sequences of Interactive Statements Stored in a File
•
How are they used?
– A lot like what we have been doing in the command window (but now we can
save our work and make changes later)
– Have no input or output parameters (which we will find different than a function
file)
•
Side Effects and Comments
– All variables are added to the workspace (i.e., command window)
– Old variables in workspace will be replaced by those of same name
– Remember you can include comments by preceding them with a “%”
4
2
Opening an ‘.m’ file
•
How to open: File menu or white sheet
OR
5
An Example of a Script ‘.m’ file
6
3
Function m-Files: Code that communicates with the
command window and other functions script via predefined
list of input and output parameters
•
•
Similar to “subroutines” in other languages
function [outputParameterList] = functionName(inputParameterList)
List of outputs (separated by commas)
List of inputs (separated by commas)
Important Notes
• First word is always “function”
• Output list is optional and included in square brackets
• functionName must also be the same as the file name!
• Variables may be strings, matrices, vectors, etc.
7
function [output parameter List] = functionName(input parameter List)
Input parameters
Function
File
output parameters
8
4
Creating and calling a function file
•
You can “call” a function from a script file, another function file, or the
interactive mode
In my m- file called addmult.m
In the interactive node or script file
function [s,p]=addmult(x,y)
>> a=4; b=5;
s=x+y; p=x*y
>> [u,v]=addmult(a,b)
>> u=9
>> v=20
Note that input and output parameters can be different variable
names!
9
function [outputparameterList] = functionName(inputparameterList)
Function
.m file
Ex. 1: f(x)=4*x+2
1 output 1 input
Ex. 2: g(x,y)=2x2+3y2-4
1 output
2 inputs
Interactive mode
function [ f ]=Matfunc (alpha)
>> y = Matfunc(4)
f = 4*alpha + 2
y = 18
function g = newfunc (x,y)
g = 2*x^2 + 3*y^2 + 4
>> x1 = 1; y1 = 3;
>> p= newfunc (x1 , y1)
p = 33
Ex. 3: f(x,y)=2x2+3y2+4
g(x) = 4x+3
2 outputs
2 inputs
Ex. 4: general form:
function [f , g]= Balhoff (x,y)
>> X2 = 2; Y2 = 1;
f = 2*x^2 + 3*y^2 + 4
g = 4*x + 3
>>[m1,m2]=Balhoff(X2,Y2)
function [f,g,h]= Cfunc(x,y,z)
m1= 15
m2=11
>> [a,b,c]=Cfunc(x1,x2,x3)
f, g, and h are complicated
functions of x, y and z
function name
List of outputs (separated by commas) List of inputs (separated by commas)
- Note: In case of multiple outputs, if we assign only one output in interactive mode,
MATLAB will return only the first output of the function.
10
5
Example of a function ‘.m’ file
function name
List of inputs (separated by commas)
List of outputs (separated by commas)
11
Primary and Secondary Functions
•
•
•
Multiple functions allowed per m-file
First function is primary function (file name too of course)
All other functions are subfunctions
(Listing 3.6 in Recktenwald)
12
6
13
Input and Output (I/O) is important in programming!
>>
x = input (‘Enter a value for x’)
Enter a value for x
% Asks for input from user
x=
4
The disp function takes only one argument
>> disp (‘My favorite color is red’)
My favorite color is red
Displaying a message along w/ numeric variable requires converting to a string
>> x = 4;
>> outstring = [‘x = ‘,num2str(x)];
>> disp(outstring)
x=4
14
7
fprintf command has much more control over what is
printed out
•
fprintf(format)
>> fprintf(‘Warning: x is negative\n’); % \n tells it to goto next line
•
fprintf(format,variable)
>> name = ‘Elvis’; age= 17;
>> fprintf(‘%s is %d years old\n’, name, age);
integer
go to next line
string
Elvis is 17 years old
•
fprintf(fid,format,variables) – Prints data to a file (better than the ‘save’
command)
>> k=1; x(k)=6;
>> fid=fopen(‘myfile.dat’,’wt’);
>> fprintf(fid, ‘k x(k)’\n’);
>> fprintf(fid, ‘%4d %5.2f’\n’, k, x(k));
15
Objective
• Create a script file (Beer.m) to make a plot of Surface area versus can
height for a 12 oz can (355 cm3)
• The m-file should request inputs of the can volume and an array of can
heights
• The m-file should call a function to calculate the surface area using the can
dimensions
• Use the plot to determine which has more surface area; Miller Lite height =
12 cm, Coors Light = 14 cm, V = 355 cm3
16
8
Matlab Programming
• Two types of m-Files (all files saved as a ‘.m’ file)
– Script m-Files
– Function m-Files
• Script m-Files are like the interactive mode, but we can
– Save our programs
– Edit our programs
– Do a lot more
• Function files are like “black boxes”
– Send some input variables; it sends back some output variables
– Matlab has thousands of built-in functions - we have already used
some!
– Always name the m-file the same as the function name!
17
Relational Operators
•
Comparison between two variables
•
Result is either true (positive integer) or false (zero)
>> a = 2; b=4
>> aIsSmaller = a < b
aIsSmaller =
1
% Define some variables
% Check to see a is less than b
>> bIsSmaller = b < a
bIsSmaller =
0
% Check to see if b is less than a
% “1” means “TRUE”
% 0 means “FALSE”
18
9
19
If…else…end
•
Programs need to make “choices”
•
“If” statements allow for programs to deal with
decisions based on conditions
if expression
block of statements
end
False
If
statement
True
commands
Some examples
if a < 0
disp(‘a is negative’)
end
End
% Asks “if” a is less than zero
% if so, then print ‘a is negative’
% end the block
20
10
There may be more than one option
if expression
block of statements
elseif expression
block of statements
elseif expression
block of statements
end
• ‘elseif’ allows for multiple options
• If a condition is true, the block of statements is
completed and then goes to end
• Possible several conditions are true, but
ignores any conditions after the first!!!
if x >= y
c = x^2 –y; % computes c “if” x is greater than or equal to y
elseif y/x > 0.0
c = log(y/x); % computes c differently,
False
% if y/x greater than 0
False
elseif
statement
end
If
statement
True
Command
Group 1
True
1) What if x=-4; y=-3?
Command
Group 1
Command
Group 1
2) What if x=4; y=3 ?
End
3) What if x=-4; y=3 ?
21
If…else…end
• ‘elseif’ block only evaluated if previous conditions false AND the
condition is true.
• Sometimes all tests will be false and nothing will happen
• Alternative is the “if…else…end”
if
x >= y
c = x^2-y;
elseif y/x > 0.0
c = log(y/x)
else
fprintf(‘WARNING: either x and y are both negative or x <y\n’)
fprintf(‘x = %f
y= %f\n’,x,y);
end
22
11
Loops are a powerful programming tool
•
Used for tasks requiring repetition of a block of statements
1.
2.
•
Traverse the elements of a vector or matrix – ‘for’ loop
Iterations repeated until a termination criterion is met – ‘while’ loop
Implemented in MATLAB with “for…end” and “while…end”
for index = expression
block of statements
end
while expression
block of statements
end
23
Examples of “for” loops
% Ex. 1 sum up all the numbers in the x-array
x = linspace(0,100)
% Create the array
sumx=0;
% initialize the sum=0
for k=1:length(x)
% loop through the x array
sumx=sumx+x(k);
% add x(k) to the current sum
end
% Ex. 2 sin(y) at varying increments
for y=0:pi/15:pi
% loop through y values by increments
disp(sin(y));
end
24
12
Nested Loops are loops inside loops
•
Loops can be nested within each other (you can do loops inside of loops)
•
Especially useful for looping through a matrix
A = …..
% Some N x M matrix
for i = 1:N
% loops through the rows of A
for j=1:M
% loops through columns using current value of i
B(i,j)=2*A(i,j)+1
end
end
•
i=1
–
–
–
–
•
i=2
–
–
–
–
•
•
j=1
j=2
…
j=M
j=1
j=2
…
j=M
i=3
…
i=N
25
“while” loops
•
Useful when calculations are repeated an undetermined number of times
•
Typical of iterative procedures
% Ex. Keep dividing x in half until it is less than 0.01
x = 1;
% Set x=1
while x > 0.01
% continue the loop “while” x is still greater than 0.01
x=x/2;
% divide x in half
end
disp(x)
•
Works similar to “for” loops, except stops when some criterion met
26
13
The “break” command
•
“break” command is an escape from the loop
•
Can prevent the loop from continuing forever
•
When encountered, the loop is immediately terminated
for i = 1:5
if i ==3
% check if i is equal to 3
break;
% break the loop
end
fprintf(‘i = %d\n’,i)
% print the current value of i
end
disp([‘End of loop!’])
% display the comment
-----------------------------------------------------------------------------------------------------i=1
i=2
End of loop!
27
Vectorization: transformation of code that operates on
scalars to code that operates on vectors
•
•
•
Sometimes replaces a “for” or “while” loop and is much quicker/easier
Sort of a ‘short-hand’ version of a loop
We have done some of this, but we’ll expand
Ex 1: Assume that you want to create these 2 matrices:
x = [ 10
y= [
20
sin(10)2+10
30
40
50 ]
sin(20)2+20
…. Sin (50)2+50 ]
There are two ways:
Using loops and scalars operation
for i = 1:5
x(i) = 10 * i
y(i) = sin(x(i)^2) + x(i)
end
Using vector operation
x = 10 : 10 : 50
y = sin(x.^2) + x
28
14
Vectorization: transformation of code that operates on scalars to
code that operates on vectors
Ex 2: Assume that you want to create these 3 matrices:
x = [ 10
20
30
40 ]
y = [ 50
60
70
80 ]
z = [ sin(10*50)/sin(50/10)
sin(20*60)/sin(60/20) …… sin(40*80)/sin(80/40) ]
There are two ways:
Using loops and scalars operation
Using vector operation
for i = 1:4
x(i) = 10 * i
y(i) = 10 * (i + 4)
z(i) = sin(x(i)*y(i)) / sin(y(i)/x(i)
end
x = 10 : 10 : 40
y = 50 : 10 : 80
z = sin (x.*y)./sin(y./x)
1. Inefficient to evaluate x(i) , y(i) and z(i) one at a time
2. MATLAB must expand vectors for memory
29
3. And the vector notation is easier to grasp
Vectorization can be used for Copy and Replace Operations
Ex.1: Copying 1st column of A to 1st column of B
>> A = [1 2 3; 4 5 6; 7 8 9]; B = ones(size(A));
1
A   4
 7
2
5
8
Scalar Code
for i=1:3
B(i,1) = A(i,1)
end
3
6 
9 
1
B   1
 1
=
1
1
1
1
1 
1 
Vector Code
B(:,1) = A(:,1)
We already did this in Chapter 2.
30
15
Vectorization can be used for Copy and Replace Operations
Ex.2: Replacing some elements of B by some elements of A
A and B are some big matrices from (m by m) and (n by n) dimensions

 a11 ... a1m1... a1m 2 .... a1m 


 ... ....

...
...


A 
 ... ...
...
...  B  



amm 
...
 ... ...



Scalar Code
for i=m1:m2
??? NOT EASY
b11
...
...
...
...
bn1 2
..
...
...
...
...
bn 2 2
...
...
...
...
...
...
b1n 
... 
... 

... 
... 

bnn 
Vector Code
temp = A (1, m1:m2)
A (1, m1:m2) = B(n1:n2 , 2)
B(n1:n2 , 2) = temp
=
end
31
Preallocating Memory…a good idea
•
MATLAB automatically increases the size of a matrix (or vector) to
accommodate new elements (not all programs do this)
– BUT it is usually a good idea to preallocate the memory
•
Involves creating the matrix with one vectorized statement beforehand
– The “ones” and “zeros” functions are typically used to preallocate memory
y = [ 2 3 5 -2 3 4 1];
y = [ 2 3 5 -2 3 4 1];
for j=1:length(y)
s = zeros(size(y));
for j=1:length(y)
if y(j)>0
if y(j)>0
s(j) = sqrt(y(j));
else
s(j) = 0;
end
OR
s(j) = sqrt(y(j));
end
end
end
32
16
Variable Number of Input and Output Arguments
function [out1,out2,…] = functionName(in1,in2,…)
• When you call a function in the workspace or main program, MATLAB
automatically recognizes the number of inputs and outputs you send to the
function.
• There are two built-in variables (nargin and nargout) which can recognize and
store the number of inputs and outputs:
– nargin : means number arguments input
– nargout : means number arguments output
•
You don’t need to define nargin and nargout. They are there! and can be simply
used by programmer.
33
Variable Number of Input and Output Arguments
Ex. : Function example.m can calculate the summation and the product of the inputs:
>> a=2; b=3; c=4;
>> [sum1,prod1]=example(a,b,c)
sum1=9 prod1=24
>> [sum2,prod2]=example(a,b)
sum2=5 prod2=6
>> [sum3]=example(a,b)
sum3=5
34
17
Variable Number of Input and Output Arguments
• So, by using nargin and nargout you could change the number of inputs and outputs in
the example.
• Note that if we did not use nargin and nargout in this example, MATLAB returns error:
>> [sum3]=example1(a,b)
??? Input argument "c" is undefined.
compare it with last slide !
35
Global Variables
provide a way to bypass input and output parameter lists
•
Should not be used when standard input and output lists can do the same
– Often used by lazy programmers
– Requires understanding of all connected m-files
•
Provide direct access to variables defined in the workspace
Syntax:
global
a b c x y ….
List of all global variables
This line should be repeated in all related functions and m files
36
18
Global Variables: Example
Ex. : Compare these two identical programs with and without using global variables:
clc
clear all
x = 0.05; y = 0.06;
z = x+y ; w1 = x*y ; w2 = x*y + x/y;
f1 = func1( x, y, z, w1 )
f2 = func2( x, y, z, w1, w2 )
function f1 = func1(x,y,z,w1)
f1 = exp(w1*z-x*y) + sqrt(w1*z+x*y)
clc
clear all
global x y
x = 0.05; y = 0.06;
z = x+y ; w1 = x*y ; w2 = x*y + x/y;
f1 = func1(z, w1 )
f2 = func2(z, w1, w2 )
function f1 = func1(z,w1)
global x y
f1 = exp(w1*z-x*y) + sqrt(w1*z+x*y)
function f2 = func2(x,y,z,w1,w2)
f2 = (x*y-w1*w2)^2 - exp(w1*y-z)
or
function f2 = func2(z,w1,w2)
global x y
f2 = (x*y-w1*w2)^2 - exp(w1*y-z)
We could even globalize z !
• Avoid repeating variables in input list of functions
•
Global Variables are recognized globally in .m-files , functions and work space.
So, no need to include them in function inputs
37
19