cs227-scientific computing lecture 3-matlab programmingstraubin/scicomp_2011/lect3.pdf ·...
TRANSCRIPT
CS227-Scientific Computing
Lecture 3-MATLAB Programming
Contents of this lecture
• Relational operators • The MATLAB while statement • Function M-files vs. script M-files • The MATLAB for statement • Logical Operators • The MATLAB if statement • Random number generation
Altering the ‘flow of control’
• M-files seen so far are just sequences of commands, executed one after the other, and bundled as a single command.
• Real programs allow you to alter this straight-line execution: blocks of commands can be executed repeatedly, or skipped depending on the current value of variables.
Example: Computing Machine Epsilon
• Here is an algorithm for computing this value:
• Set x = 1, and continue dividing x by 2 until 1+x evaluates to 1.
• Machine epsilon is the next-to-last value of x obtained in this process.
Example: Computing Machine Epsilon
is 1+x the same as 1?
set x = x/2
set x = 1
yes
no
done
Example: Computing Machine Epsilon
is 1+x the same as 1?
set x = x/2
set x = 1
yes
no
done
How do we code this?
while statement
while condition statement statement
. . . end
Execute the block of statements as long as the expression evaluates to true.
while statement
while condition statement statement
. . . end
How do we encode the condition?
Relational Operators • These are <,<=,>,>==,== (is equal to), ~= (is
not equal to). • The value of an expression using one of
these operators is either 0 (false) or 1 (true). >> 7<3 ans =0 >> 3<=7 ans =1 >> 3==7 ans =0 >> 3=7 ??? 3=7 Error: The expression to the left of the equals sign is not a valid target for an assignment.
The Machine Epsilon Script
%computation of machine %epsilon
x=1; while 1+x/2~=1 x=x/2; end x
The Machine Epsilon Script
%computation of machine epsilon
x=1; while 1+x/2~=1 x=x/2; end x
Note that the original algorithm was ‘off by one’—a common problem with loop structure---and had machine epsilon as the next-to-last value of x. This is why we write the condition as 1+x/2~=1 instead of 1+x~=1.
Function M-files function s = powersin(x)
%POWERSIN Power series for sin(x). % y = POWERSIN(x) tries to compute %sin(x) from its power series.
s = 0; t = x; n = 1; while s+t ~= s; s = s + t; t = -x.^2/((n+1)*(n+2)).*t; n = n + 2; end
This example from Moller’s book is a MATLAB function that evaluates the power series for sin x at its input argument and returns the value of the sum in its output argument.
You invoke the function just as you would any built-in MATLAB function
A MATLAB function has its own private space for variable names
The variables x,y,s and n in the Command Window are completely different from the variables with the same names in the function powersin.
A MATLAB function has its own private space for variable names
The function communicates with the user exclusively through the value assigned to its input argument and the value returned in its output argument. Typically a function reads no input from the keyboard, and prints no output to the screen.
Here is the computation of machine epsilon implemented as a function
function x = whatseps2( ) %WHATSEPS2 returns machine epsilon as a value x = 1; while 1+x/2~=1 x=x/2; end
end
Note that there is no input argument. The second ‘end’, closing the keyword ‘function’, is optional. The ‘end’ closing ‘while’ is not.
Here is the computation of machine epsilon implemented as a function
If a function has no input arguments, it can be invoked with or without parentheses. In fact the built-in eps in MATLAB is a function with no arguments.
Functions can have more than one output argument
In this version of whatseps, the second output argument contains the value n such that eps = 2^n.
function [x,n] = whatseps3( ) %WHATSEPS3 returns machine epsilon as a value %and the corresponding power of two as a second %output argument. x = 1; n=0; while 1+x/2~=1 x=x/2; n=n+1; end n=-n; end
Functions can have more than one output argument
When you invoke a function with more than one output argument, you have to explicitly grab the output values after the first, or they will be ignored.
The for statement
• Syntax
• Semantics: variable is set in turn to each of the values startvalue, startvalue + increment, etc. For each of these values, the sequence of statements is executed.
for variable = startvalue:increment:endvalue statement1 statement2 . .
end
Example
• This program prints the sum of the first million terms of the harmonic series, both forward and backward.
forward_sum=0; backward_sum=0; for i=1:1000000 forward_sum=forward_sum+1/i; backward_sum=backward_sum+1/(1000000-i+1); end forward_sum backward_sum
Warning!
• MATLAB is different from other programming languages, in that it is optimized to perform vectorized operations rapidly.
• The use of for loops is sometimes unavoidable, but in this case it is much faster to sum the harmonic series by with the statement sum(1./1:1000000).
• See “Vectorizing Loops” under “Techniques for Improving Performance” in MATLAB Help.
Random number generation • The built-in MATLAB function rand() returns a
value uniformly distributed between 0 and 1.
• We’ll have a LOT more to say about random numbers later in the course!
>> rand() ans =
0.8147 >> rand() ans =
0.9058 >> rand() ans =
0.1270
Example: A random walk • This program returns the result of a random walk. At each step, a
random angle between 0 and 2π is generated, and a step of length 1 is taken in that direction.
function x = randomwalk( numsteps )
%RANDOMWALK A random walk in the plane % Each step is of length 1 in a random direction % numsteps is the total number of steps % x is a 2 x numsteps matrix giving the coordinates of %the points visited in the walk
x=zeros(2,numsteps);
for step=2:numsteps theta=2*pi*rand(); x(:,step)=x(:,step-1)+[cos(theta);sin(theta)];
end
Example: A random walk
• Plots from two sample runs of the program:
Example: Nested for statements
• This script computes and prints Pascal’s triangle: The triangular array of binomial coefficients C(n,k),where 0<=k<=n.
• These are computed by the formulas C(n,0)=C(n,n)=1, C(n+1,k+1)=C(n,k+1)+C(n,k).
vec=zeros(11,11); vec(1,1)=1; fprintf('%d\n',vec(1,1)) for row=2:11 vec(row,1)=1; fprintf(‘%d\t’,vec(row,1)); for col=2:row vec(row,col)=vec(row-1,col)+vec(row-1,col-1); fprintf('%d\t',vec(row,col)); end fprintf('\n'); end
Example: Nested for statements
• A run of the program
>> pascaltriangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 >>
Logical Operators • Expressions with value true or false can be
combined using && (and), or (||) and not (~). • For instance, the expression below is true if and
only if n is a leap year (divisible by 4, and not divisible by 100 unless it is divisible by 400). Note the use of rem(n,k), which returns the remainder of n upon division by k.
(rem(n,4)==1)&&((rem(n,100)~=0)||(rem(n,400)==0))
The if statement if condition
statement statement . .
end
if condition statement statement . . .
else statement statement . .
end
if condition statement statement . . .
elseif condition statement statement . .
elseif condition statement statement . .
else statement statement . .
end
Example: A version of the random walk in which every step is horizontal or vertical, with each of the four directions
equally probable.
function x = randomwalk2( numsteps ) %RANDOMWALK A random walk in the plane % Each step is 1 step north, south, east or west % numsteps is the total number of steps % x is a 2 x numsteps matrix giving the coordinates of %the points visited in the walk x=zeros(2,numsteps);
for step=2:numsteps r=rand(); if r<0.25 x(:,step)=x(:,step-1)+[1;0]; elseif r<0.5 x(:,step)=x(:,step-1)+[-1;0]; elseif r<0.75 x(:,step)=x(:,step-1)+[0;1]; else x(:,step)=x(:,step-1)+[0;-1]; end end
A plot of the output is peculiar-looking!
Example: This executes the random walk until it wanders a specified distance from the origin.
function [ X n ] = randomwalk3( radius ) %RANDOMWALK3 A random walk with each step of length 1 in a random %direction. The walk continues until it wanders a distance of %radius from the origin. % X is a 2-row matrix giving the coordinates of the successive % points on the walk. n is the total number of steps taken. %Note that we build the matrix X one column at a time. X=[0;0]; n=1; while(X(1,n)^2+X(2,n)^2<= radius^2) theta = 2*pi*rand(); y = X(:,n)+[cos(theta);sin(theta)]; X = [X y]; n=n+1; end end
Example: In this version, the random walk proceeds until either the required distance from the origin is reached, or
the maximum allowable number of steps are taken.
function [ X n ] = randomwalk4( radius, maxsteps ) %RANDOMWALK3 A random walk with each step of length 1 in a random %direction. The walk continues until it wanders a distance of %radius from the origin, or until it takes maxsteps steps, whichever %comes first. % X is a 2-row matrix giving the coordinates of the successive % points on the walk. n is the total number of steps taken. % Note that we pre-allocate a matrix X large enough to hold all the % steps, and then trim it to the correct size. X=zeros(2,maxsteps); n=1; while((X(1,n)^2+X(2,n)^2<= radius^2)&&(n<=maxsteps)) theta = 2*pi*rand(); X(:,n+1) = X(:,n)+[cos(theta);sin(theta)]; n=n+1; end %trim unused columns from the matrix X=X(:,1:n); end