Professional Documents
Culture Documents
CH 03 Slides 3
CH 03 Slides 3
Gerald W. Recktenwald
Department of Mechanical Engineering
Portland State University
gerry@me.pdx.edu
Version 0.97
Overview
Script m-les
Creating
Side eects
Function m-les
Syntax of I/O parameters
Text output
Primary and secondary functions
Flow control
Relational operators
Conditional execution of blocks
Loops
Vectorization
Using vector operations instead of loops
Preallocation of vectors and matrices
Logical and array indexing
Programming tricks
Variable number of I/O parameters
Indirect function evaluation
Inline function objects
Global variables
page 1
Preliminaries
page 2
Script Files
page 3
(1)
page 4
(2)
tan()
-1
-2
-3
-4
-5
2.5
3.5
4.5
(radians)
page 5
%
%
plot(x,y)
% Generate the plot and label it
xlabel(x axis, unknown units)
ylabel(y axis, unknown units)
title(Plot of generic x-y data set)
page 6
page 7
page 8
page 9
Syntax:
The rst line of a function m-le has the form:
function [outArgs] = funName(inArgs)
page 10
page 11
twosum.m
function twosum(x,y)
% twosum Add two matrices
%
and print the result
x+y
threesum.m
function s = threesum(x,y,z)
% threesum Add three variables
%
and return the result
s = x+y+z;
addmult.m
page 12
B = [5 6; 7 8];
>> twosum(one,two)
ans =
227
229
212
Notes:
1. The result of the addition inside twosum is exposed because the x+y
expression does not end in a semicolon. (What if it did?)
2. The strange results produced by twosum(one,two) are obtained by
adding the numbers associated with the ASCII character codes for each
of the letters in one and two.
Try double(one) and double(one) + double(two).
page 13
page 14
page 15
page 16
page 17
Inputs to functions:
page 18
The input function can be used to prompt the user for numeric
or string input.
>> x = input(Enter a value for x);
>> yourName = input(Enter your name,s);
page 19
fprintf
page 20
Syntax:
disp(outMatrix)
disp(x)
2
3
>> y = 3-x;
1
2
disp([x; y])
2
3
1
0
Note: The last statement shows that the input to disp must
be a legal matrix.
page 21
disp(s)
length(S(1,:))
page 22
0
0
1
>> S = num2str(A)
S =
1 0 0
0 1 0
0 0 1
page 23
0
0
0
>> whos
Name
Size
A
B
S
ans
3x3
3x3
3x7
3x3
B = str2num(S);
0
0
0
Bytes
72
72
42
72
Class
double array
double array
char array
double array
page 24
(1)
page 25
(2)
The
disp([x = ,num2str(x)]);
disp(z)
page 26
(3)
>> z
z =
1
2
3
4
page 27
page 28
Syntax:
fprintf(outFormat,outVariables)
fprintf(fileHandle,outFormat,outVariables)
Notes to C programmers:
1. The Matlab fprintf function uses single quotes to dene
the format string.
2. The fprintf function is vectorized. (See examples below.)
Example:
>> x = 3;
>> fprintf(Square root of %g is %8.6f\n,x,sqrt(x));
The square root of 3 is 1.732051
page 29
Conversion instruction
%s
format as a string
%d
%f
%e
%g
\n
\t
page 30
Meaning
%14.5f
%12.3e
page 31
%8.4f
%12.3e
%10g
%8d
2.0000
2.000e+00
sqrt(2)
sqrt(2e-11)
1.4142
0.0000
1.414e+00
4.472e-06
1.41421
4.47214e-06
1.414214e+00
4.472136e-06
447213.5955
4.472e+05
447214
4.472136e+05
sqrt(2e11)
page 32
page 33
page 34
page 35
width
(cm)
5
5
10
15
height
(cm)
5
8
15
25
depth
(cm)
15
15
20
35
volume
(m^3)
0.03750
0.06000
0.30000
1.31250
page 36
page 37
page 38
Meaning
less than
less than or equal to
greater than
greater than or equal to
not equal to
page 39
y = 5:-1:1;
page 40
Logical Operators
Meaning
and
or
not
Examples:
>> a = 2; b = 4;
>> aIsSmaller = a < b;
>> bIsSmaller = b < a;
>> bothTrue = aIsSmaller & bIsSmaller
bothTrue =
0
>> eitherTrue = aIsSmaller | bIsSmaller
eitherTrue =
1
>> ~eitherTrue
ans =
0
page 41
Summary:
Free Advice:
page 42
Conditional Execution
page 43
if Constructs
Syntax:
if expression
block of statements
end
Example:
if a < 0
disp(a is negative);
end
page 44
if. . . else
Multiple choices are allowed with if. . . else and if. . . elseif
constructs
if x < 0
error(x is negative; sqrt(x) is imaginary);
else
r = sqrt(x);
end
page 45
if. . . elseif
is positive);
0
is negative);
is exactly zero);
page 46
Example:
color = ...;
%
switch color
case red
disp(Color
case blue
disp(Color
case green
disp(Color
otherwise
disp(Color
end
NMM: Matlab Programming
color is a string
is red);
is blue);
is green);
is not red, blue, or green);
page 47
Repetition or Looping
A sequence of calculations is repeated until either
1. All elements in a vector or matrix have been processed
or
2. The calculations have produced a result that meets a
predetermined termination criterion
Looping is achieved with for loops and while loops.
page 48
for loops
for loops are most often used when each element in a vector or
matrix is to be processed.
Syntax:
for index = expression
block of statements
end
page 49
page 50
1
rk =
2
rk1 +
rk1
r = ...
% initialize
rold = ...
while abs(rold-r) > delta
rold = r;
r = 0.5*(rold + x/rold);
end
NMM: Matlab Programming
page 51
page 52
page 53
page 54
page 55
function k = demoReturn(n)
...
...
while k<=n
if x(k)>0.8
break;
end
k = k + 1;
end
while k<=n
if x(k)>0.8
return;
end
k = k + 1;
end
return to calling
function
page 56
Vectorization
page 57
Scalar Code
for k=1:length(x)
y(k) = sin(x(k))
end
Vectorized equivalent
y = sin(x)
page 58
Preallocate Memory
y = ...
% some computation to define y
s = zeros(size(y));
for j=1:length(y)
if y(j)>0
s(j) = sqrt(y(j));
end
end
page 59
3.4641
4.0000
4.47210
page 60
Logical Indexing:
Use a vector or matrix as the mask to select elements from
another matrix:
>> x = sqrt(0:4:20)
x =
0
2.0000
2.8284
3.4641
4.0000
4.47210
>> j = find(rem(x,2)==0)
j =
1
2
5
>> z = x(j)
z =
0
2
page 61
page 62
%
%
for i=1:m
B(i,1) = A(i,1);
end
Vectorized Code
B(:,1) = A(:,1);
page 63
Vectorized Code
B(1,2:3) = A(2:3,3)
page 64
Deus ex Machina
page 65
page 66
nargout
plot(x,y)
plot(x,y,s)
plot(x,y,s--)
plot(x1,y1,s,x2,y2,o)
h = plot(x,y)
page 67
page 68
>> fsum(sin,0,pi,5)
ans =
2.4142
>> fsum(cos,0,pi,5)
ans =
0
page 69
Use of feval
function s = fsum(fun,a,b,n)
% FSUM Computes the sum of function values, f(x), at n equally
%
distributed points in an interval a <= x <= b
%
% Synopsis:
s = fsum(fun,a,b,n)
%
% Input: fun = (string) name of the function to be evaluated
%
a,b = endpoints of the interval
%
n
= number of points in the interval
x = linspace(a,b,n);
y = feval(fun,x);
s = sum(y);
%
%
%
function y = sincos(x)
% SINCOS
Evaluates sin(x)*cos(x) for any input x
%
% Synopsis: y = sincos(x)
%
% Input:
x = angle in radians, or vector of angles in radians
%
% Output:
y = value of product sin(x)*cos(x) for each element in x
y = sin(x).*cos(x);
page 70
Use
myFun = inline( x.^2 - log(x) );
Usefulness:
page 71
Global Variables
x
y
s
z
=
=
=
=
1
2
1.2
localFun(x,y,s)
localFun.m
(x,y,s)
z
d = a + b^c
workspace
x = 1;
y = 2;
global ALPHA;
...
ALPHA = 1.2;
z = globalFun(x,y)
(x,y)
(a,b)
function d = globalFun(a,b)
...
global ALPHA
...
d = a + b^ALPHA;
Usefulness:
page 72