Tutorial on MATLAB - Department of Mathematics, CUHK

Download Report

Transcript Tutorial on MATLAB - Department of Mathematics, CUHK

Department of Mathematics
Chinese University of Hong Kong
Prepared and revised by Raymond Chan
1
1
• What is MATLAB?
• MATLAB Demo
2
2
What is MATLAB?
•
•
•
•
•
•
MATrix LABoratory
Calculator
Interactive
Programming language
Scientific computation and visualization tool
Symbolic computing tool
3
3
Matrix Computations
Define a matrix and vector:
>> A=[1 2 3; 4 5 6; 7 8 9]
>> b=[pi, exp(1), sin(0.1)]
Matrix-vector multiplication:
>> c=b*A
>> d=A*b’
Matrix operations
>> determinant=det(A)
>> eigenvalue=eig(A)
4
4
2D Graphics
Polar plot:
t=0:.01:2*pi;
polar(t,abs(sin(2*t).*cos(2*t)));
Line plot:
x=0:0.05:5; y=sin(x.^2); plot(x,y);
Stem plot:
x = 0:0.1:4; y = sin(x.^2).*exp(-x);
stem(x,y)
5
5
3D Graphics
Surface plot:
z=peaks(25); surf(z);
Mesh plot:
z=peaks(25); mesh(z);
Contour plot:
z=peaks(25); contour(z,16);
Spherical harmonic: spharm2
6
6
Symbolic Computations
Differentiation:
>> g=sin(x)*cos(y);
>> diff(g)
% differentiate w.r.t. x
>> diff(g,y,3)
% 3rd order partial derivative w.r.t. y
Integration:
>> g=(y^2-1)/(x^5+1); int(g,y) % integrate w.r.t. y
7
7
MATLAB Desktop
To start MATLAB: Programs => MATLAB => MATLAB 7.12
Workspace
Window:
show what
variables
in memory
Command
Window:
Directory
Window:
where you
input
MATLAB
commands
show the
files in the
directory
History
Window:
record
what you
have done
8
8
•
•
•
•
MATLAB as Calculator
Scalar Variables
Vectors and Matrices
Basic Matrix Operations
9
9
MATLAB as Calculator
Just enter after the prompt “>>”:
2+2
100-43
3*3
5/2
2^8
log(2)*sin(pi/2)
acos(-1)/exp(4)
10
MATLAB References
• Upper and lower case characters are not
equivalent (MATLAB is case sensitive).
• Typing the name of a variable will cause
MATLAB to display its current value.
• MATLAB uses parenthesis ( ), square bracket [ ],
and curly braces { }, and most standard
characters, such as a to z, A to Z, %, ^, +, -, *, /.
11
11
MATLAB References
• Type help topic to access online help on a command,
function or symbol topic (e.g. help cos). Hyperlinks,
indicated by underlines, are provided that will take
you to related help items and the Help browser.
• Use lookfor topic (e.g. lookfor cosine) if you are not
certain what the name of the topic is
• If you press the tab key after partially typing a
function or variable name, MATLAB will attempt to
complete it, offering you a selection of choices if
there is more than one possible completion.
12
12
Samples of Math Operators and Functions
Operators
+
^
/
Functions
Addition
sin
cos
Subtraction
sinh
cosh
Multiplication
floor
ceil
Exponentiation
exp
log
``Left'' division
sqrt
abs
``Right'' division
real
imag
You can find that by going to :
http://www.mathworks.com/help/matlab/ref/arithmeticoperators.html
More general function names can be found at:
http://www.mathworks.com/help/matlab/index.html
13
Scalar Variables
Variables are locations to store values and results.
For example, try this:
>> x = 2
This assigns the value 2 to the variable x.
To see what’s inside x, type:
>> x
Now try:
>> y=4
>> x+y
14
Scalar Variables
This:
>> z = 3;
assigns the value 3 to the variable z without
printing it.
You can have variable name like: X, A2, x_y
Cases are sensitive: x is not the same as X
15
Built-in Variables
Three built-in variables are: pi, i, j, where
pi= ,i,j= -1
Not good to re-assign pi as a variable. To reset i:
>> clear
or
>> i = sqrt(-1)
16
Who’s Who in My Memory
To know what you have assigned or computed:
b=2
c = [2,3,5]
d = [4;1;3;-1]
e = 'words, words, words'
f = [7,9;8,5]
who
whos
17
Vectors and Matrices
How to input:
rvec = [1 2 3]
cvec = [4
3
4
2]
mat = [3 3 4
456
9 9 0]
 3 3 4
4 5 6


9 9 0
cvec = [4
3
4
2]
mat = [ 3 3 4
456
9 9 0]
18
Or simply:
 3 3 4
4 5 6


9 9 0
rvec = [1, 2 3]
cvec = [4; 3; 4; 2]
mat1 = [3 3, 4; 4 5 6; 9, 9 0]
Faster way of generating vectors and matrices:
zeros(4,3) = 4-by-3 zero matrix
ones(1,4)
=[1, 1, 1, 1]
eye(4,4)
=4-by-4 identity matrix
rand(4,1)
=4-by-1 random matrix
[1:4]
=[1, 2, 3, 4]
[start:stepsize:end]
[1:0.5:3]
=[1, 1.5, 2, 2.5, 3]
[3:-0.5:1]
=[3, 2.5, 2, 1.5, 1]
19
Controlling Output
>> x=2.3909302;
>> format long; x
2.390930200000000
>> format long e; x
2.390930200000000e+000
>> y=239.09302;
>> format short e; y
Scientific or
2.3909e+002
Exponential notation
>> format short; y
239.0930
20
Controlling Output
>> A=[1,2,3,4;5,6,7,8];
>> A(2,3)
7
>>A(2,:)
5 6 7 8
>> A(:,3)
3
7
>>A(2,2:4)
6 7 8
21
1 2 3 4
5 6 7 8


Some Useful Commands
quit, exit
diary
clear
help XX
who
whos
lookfor XY
clc
;
%
quit MATLAB
log the session
clear all variables in the memory
help on the command XX
what variables in memory
size of the variables
search command related to XY
clear command window
suppress printing
comments (matlab will not read)
22
Basic Matrix Operations
C = [3 1 1; 0 2 4 ; -1 0 1]
d = [2 3 4]
e = d'
size(C)
length(d)
3*C
C*e
C*C
C\e
d/C
C^2
% C is a 3-by-3 matrix
% d is a row vector
% e is transpose of d
% size of C
% length of d
% scalar multiplication
% matrix-vector product
% matrix-matrix product
% solution to C x = e
% solution to d = x C
% square of C = C*C
23
Entry-wise Operations
3.*A
A+B
A–B
A.*B
A./B
A.^2
A+3
= 3*A
= A+B
= A-B
= ai,j * bi,j
= ai,j / bi,j
= ai,j * ai,j
= ai,j + 3
24
MATLAB notation
Right division: a/b
Left division : a\b
Mathematical equivalent
a/b
b/a
Elementary matrix and array operations:
Operation
Matrix sense
Addition
+
Subtraction
Multiplication
*
Left division
\
Right division
/
Exponentiation
^
25
Entry-wise sense
+
.*
.\
./
.^
Scalar Functions for Matrices
sin(C)
exp(C)
real(C)
ceil(C)
floor(C)
sqrt(C)
C^(1/2)
% sine of each entry of matrix C
% exponential of each entry of C
% real part of each entry of C
% round each C’s entry up
% round each C’s entry down
% square root of each entry of C
% matrix square root of C
26
Scalar Functions as Matrix Functions
Polynomial Evaluation:
Consider p(x)=2x3+4x-7, to compute p(3), use:
p=[2 0 4 -7]; x=3; y=polyval(p,x)
To compute p(x) for x in between 0 and 2, use:
y=polyval(p,[0:0.01:2])
If A is a matrix, polyval(p,A) gives
2*A.^3+4*A-7
27
• Graphics
• 2D Plots
Visualization Tools
Matlab is a powerful visualization tool. From 2D
plots to 3D plots to image processing.
contour plot
vector field
Visualization Tools
3D surface plot
view from
different
angles
image processing
compression
2D Example: y=sin(x)
x = 0:0.01:pi;
plot(x, sin(x))
3D Example: z = x * y
[x, y] = meshgrid(-3:0.1:3, -3:0.1:3);
z = x .* y;
mesh(x,y,z);
Graphics
To create a graph you run:
• Management commands:
arranging the figure windows
• Graph generation commands:
plot, mesh
• Annotation commands:
formatting the graphs
Plotting Commands: 3 categories
Management
figure
subplot
zoom
hold
close
view
rotate
Graphic
plot
semilogx
semilogy
loglog
polar
fill
bar
Annotation
title
xlabel, ylabel
text
grid
legend
box
set
Graphic command
Description
plot(x)
Plot elements of x(i) (ordinate)
versus their index number i
plot(x,y)
Plot x(i) (abscissa) versus y(i)
(ordinate)
loglog(x,y)
Plot log x(i) versus log y(i)
semilogx(x,y)
Plot log x(i) in y(i)
polar(t,r)
Plot polar plot with angle t and
magnitude r
Example:
>> plot(sqrt([16:64]))
8
7.5
7
6.5
6
5.5
5
4.5
4
0
5
10
15
20
25
30
35
40
45
50
Example:
x=[0:0.1:10];
semilogy(x,exp(x));
105
104
103
102
101
100
0
1
2
3
4
5
6
7
8
9
10
Example:
t=[0:0.1:10];
polar(t,t);
90
120
150
10
8
6
4
2
60
30
180
(x,y)=(tcost, tsint)
0
210
330
240
300
270
• The command
>> plot([x1 x2] , [y1 y2])
plots a straight line form (x1 , y1) to (x2 , y2)
• The command
>> plot(x, y)
plot a set of straight lines connecting
(xj , yj) and (xj+1 , yj+1)
Example:
>> x = [1.2 2.3 3.7 4.1 5.0 7.3];
>> y = [2.6 2.8 3.7 4.0 4.3 5.6];
>> plot(x,y)
More Sophisticated Plot:
>> plot(x,y, 'string')
• string stands for color, marker and line type
• E.g.: 'r*-' means red, asterisk at each data
point, and join points by solid line.
• Plotting many curves on the same figure:
>> plot(x,y, 'r-',a,b, 'g--',….)
Example:
>> x=0:0.05:pi;
>> plot(x,cos(x),'r-',x,sin(x),'mv')
Colors, Markers and Line Types
Color
y
m
c
r
g
b
w
k
yellow
magenta
cyan
red
green
blue
white
black
Marker


x
+
*
s
d
v
^
<
>
p
h
point
circle
x-mark
plus
star
square
diamond
triangle (down)
triangle (up)
triangle (left)
triangle (right)
pentagram
hexagram
Line
solid

:
dotted
.
  dashed
Annotation Commands:
Labeling function
Description
gtext('string')
Add the string at the mouse location,
activated by pressing a mouse button
or any key.
text(x, y, 'string')
Add the string at the location (x,y)
relative to axis units.
title('string')
Add the string as a title to the top of
the plot.
xlabel('string')
ylabel('string')
Add the string as an x or y axis label.
legend('string')
Add the string to describe a curve
drawn in the figure
Example:
clear all
x = 0:0.1:pi;
plot(x,sin(x),'r:o')
xlabel('x in radians')
ylabel('sin(x)')
title('This is the sine plot.')
text(1,0.5,'Text can be placed anywhere')
text(1,0.25,...
{'Text can span multiple lines', 'like this.'})
Managing the Figure Windows
• Each graph is created in a Figure Window
• By default, only one Figure Window can be
opened
• Thus the second graph will replace the first one
• To plot two or more graphs in one window, use
>> hold
• To unhold the windows, use
>> hold off
Compare:
x = 0:0.01:pi;
x = 0:0.01:pi;
plot(x, sin(x));
plot(x, sin(x));
hold
plot(x, cos(x));
plot(x, cos(x));
What if you want separate figures?
•
•
•
•
figure(n) – opens Figure Window number
n and make it the current window
subplot(i,j,k) – divides Figure Window into
i-by-j smaller windows for plotting;
k – the number of the smaller window
where you want to put your plot into
To close Figure n, use close n
To close all figures, use close all
Example:
x = 0:0.01:pi;
plot(x, sin(x));
figure(2);
plot(x, cos(x));
Example:
x = 0:0.01:pi;
subplot(2,1,1); plot(x, sin(x));
subplot(2,1,2); plot(x, cos(x));
• Matrix Functions
• Matrix Inverse
1.
inv
2.
\
3.
rref
• Determinant
• Norm
52
Matrix Functions
inv(C)
det(C)
eig(C)
[V,D]=eig(C)
norm(C)
diag(C)
rank(C)
pinv(C)
sum(C)
cross(d,e)
% inverse of matrix C
% determinant of C
% eigenvalues of C
% e-value and e-vector of C
% norm of C
% diagonal part of C
% rank of C
% pseudoinverse of C
% column sum of C
% cross product of d and e
53
Finding Matrix Inverse
Simple –– use inv (A)
>> A = rand (100, 100);
>> inv (A);
For solving Ax = b, use either
>> inv (A) * b
or
>> A \ b
54
If A is not invertible, then
* * * * *
1 0 0 * *
* * * * *
1 0 * *
* * * * *
Bk · · · B1
* * * * *
1 * *
0
* * * * *
* * * * *
Reduced Row Echelon Form
It can be obtained in MATLAB by
>> rref(A)
55
For examples
1
2
3
4
5
6
7
8
10
1
2
3
4
5
6
7
8
9
rref
rref
1
0
0
0
1
0
0
0
1
rank = 3
1
0
-1
0
1
2
0
0
0
1
0
-1
-2
-3
0
1
2
3
4
rank = 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
0
0
0
0
0
16
17
18
19
20
0
0
0
0
0
rref
56
rank = 2
Determinant
Given A = [aij]
n
det(A)   (1)i  j aij det(M ij )
j 1
n
  (1)i  j aij det(M ij )
i 1
where Mij is the submatrix obtained by
deleting row i and column j.
Why compute det(A)?
det(A) = 0  A is singular
Logical Flow
• Relation and logical operators
• Controlling statements: for, while and if
58
Relational and Logical Operators

Relational operators available:
<, <= (less than or equal to), >, >=,
== (equal), ~= (not equal)

Logical operators to combine relational
expressions: & (and), | (or), ~ (not)
if ((b>=a) & (b>=c))
disp('b is the maximum')
end
59
Control-of-Flow Constructs
for, while, if




Fixed repetition – the for loop
Indefinite repetition – the while loop
Single decision – the if/else construct
Multiple options – the if/elseif/else contruct
60
Control Statements

MATLAB has three control constructs:


for, while, if
for is an iterated loop statement
for i = 1:n
…
…
…
end

% loop body statements
% every statement here is
% repeated n times
or
for i = m:s:n
…
% from m to n in steps of s
end
61
Example: for
% to compute the sum from 1 to 10
sum = 0;
for i = 1:10
for i-loop
sum=sum+i;
end
% this can also be done by sum(1:10)
62
Example: for
% to compute the factorial of 10
fact = 1;
for i = 2:10
fact = fact*i;
end
% this can also be done by factorial(10);
63
Example: for
% sum a random vector
a = rand(1,100);
sum = 0;
for i = 1:100
sum = sum+a(i);
end
disp(sum)
% this can also be done by sum(a);
64
Example: for
% sum only the odd-index entries
a = rand(1,100);
sum_odd = 0;
for i = 1:2:100
sum_odd = sum_odd+a(i);
end
disp(sum_odd)
65
Example: Nesting for-loop
Nesting refers to the act of putting a for-loop
within a for-loop
% to generate a k-by-k Hilbert matrix
1
k=5;

 1/ 2
A = zeros(k,k);

 1/ 3

for m = 1:k
 

for n = 1:k
A(m,n) = 1/(m+n -1);
end % for n - loop
end % for m - loop
A
1/ 2
1/ 3
1/ 3






 


1 /(2n  2)
1 /(2n  2) 1 /(2n  1) 

66
Example: Nesting for-loop
% Matrix multiplication C = A*B
k
C (m, n)   A(m, j ) B( j, n),
1  m, n  k.
j 1
C=zeros(k,k);
for m = 1:k
for n = 1:k
for j = 1:k
C(m,n) = C(m,n) + A(m,j)*B(j,n);
end
% for j – loop
end % for n - loop
end % for m - loop
67
While Control
while construct:
while <condition>
…
% every statements here
…
% will be repeated until
…
% condition is not satisfied
end
68
Example: while
% sum a random vector
a = rand(1,100);
s = 0;
j=1; % set the test variable
while j < 101
s = s+a(j);
j = j+1; % update test variable
end
% the same program using
% for-loop
% sum a random vector
a = rand(1,100);
s = 0;
for i = 1:100
s = s+a(i);
end
69
Sum 1:n until total > N
% sum 1 to n until total sum > N
sum=0; i=0;
while sum < N % N to be input
i=i+1;
sum=sum+i;
end
disp([i,sum]) % # of terms and total
70
Sum rand until rand < 0.9
% an example of indefinite repetition
% (i.e. we don’t know when it will stop)
%
% sum as many random numbers
% as possible as long as they are
% less than 0.9
%
s = 0;
while rand<0.9 % while the random number is less than 0.9
s = s+rand % sum the random number
end
71
If Control
if construct:
if <condition>
…
% do this if condition is true
else
…
% do that otherwise
(elseif <condition>)
(…)
% you can have more conditions
end
72
Example: if/elseif/else
if A > B
if A > B
disp('A is larger')
else disp('A is not larger')
end
disp('A is larger')
elseif A < B
disp('B is larger')
elseif A == B
disp('A equals B')
else disp('Unexpected situation')
end
73
Example: if/elseif/else
% score(j) is the score of j-th student
for j=1:class_size
if score(j) >= 90
grade(j)='A';
elseif score(j) >= 80
grade(j)='B';
else
grade(j)='F';
end
end
74
• Programs
• Scripts
75
Why programs
When we want to do
something repeatedly.
Suppose we want to
see if the average of
1,000 uniformlydistributed random
numbers is close to 0.5.
a = rand(1000,1);
s = 0;
for i = 1:1000
s = s+a(i);
end
s/1000
What if we want to
run this several times?
76
• Copy the commands, and then paste it to
MATLAB prompt >> every time you
want to repeat the commands
• Or, save the commands into a file, and
then enter the filename at the MATLAB
prompt >>. Then MATLAB will run
every command in the file. The file is
called a MATLAB program or a script.
• MATLAB scripts (or simply M-scripts)
must have file extension .m.
77
To create a MATLAB script
• In the “Command Window”
• Select the “File” menu command
• Select “New / script”
This should start the m-script Editor Window.
Type your program into the window.
78
Command Window
Enter your
program here
Editor Window
79
To save:
• Select the menu command File/Save and
give the program an appropriate name, e.g.
testavg. The ‘.m’ file extension should
automatically be added to the program
name.
• The file will be saved into your work space.
(See the Current Folder Window.)
• Click back to the Command Window.
• You can check if your program is there by
the MATLAB command dir *.m.
80
To Run a Script:
Type the name of the program without the ‘.m’
and hit “Enter”. E.g.
>> testavg
ans=
0.4917
The program runs and gives you the result.
To run it again, just do the same:
>> testavg
It will give you another average.
81
Advantage of Writing Programs
•
Easier to run than copy and paste
•
Easier to make corrections and changes
•
Programs reside on disk, can recall in the
future
•
Can share between different computers
•
Allow different inputs and outputs
•
Can combine different programs to do
complicated tasks.
82
Don’t lose your head:
• Give some explanations
and details of the
programs’ operations
• Comment them by
using % at the
beginning of each
comment.
Typing ‘help testavg’ will
display this header.
% testavg compute
% the average of
% 1000 random
% numbers
a = rand(100,1);
s = 0;
for i = 1:100
s = s+a(i);
end
s/100
83
An Example of MATLAB Program
% a program called multiply.m
% take two variables and multiply them
a=5;
b=3;
product = a * b
Type this into your editor, save it with the name
“multiply.m” and ‘run’ it with the command
>> multiply
84
Input the Arguments
Sometimes we want to
change the results of the
program by changing some
of the input variables.
n=input('n= ')
For example, we may want
to compute the average of n
numbers instead of 1,000
numbers where n is given by
the user of the program.
for i = 1:n
a = rand(n,1);
s = 0;
s = s+a(i);
end
s/n
85
A Simple Program with 2 Inputs
% a program called multiply.m
% take two variables and multiply them
a=input('a= ')
b=input('b= ')
product = a * b
Type this into your editor, save it with the name
“multiply.m” and ‘run’ it with the command
>> multiply
86
To sketch a surface :
To graphs the function z=xp+yp for different p,
enter the followings and save as sketch.m:
[x, y] = meshgrid(-3:0.1:3, -3:0.1:3);
z = x .^p + y .^p;
mesh(x,y,z);
Type >> p=2; sketch
and >> p=4; sketch
What will the shape be for p odd, and for p large?
87
Output the Results
First is to print them without the “;”
% a simple program
a = 7;
b = 3;
c = a+b;
c
the result of c is presented.
88
disp is another simple command for displaying numbers or
text on the screen.
>> c=10; disp(c)
% number
>> A=[1 2; 3 4]; disp(A)
% matrix
>> c=10; d=20; disp([c, d])
% vector of numbers
>> t='Raymond'; disp(t)
% text
>> s='Hello'; t='Ray'; disp([s, t])
% vector of texts
>> c=10; disp([' c = ', num2str(c)]) % text/number > text
For more sophisticated output formats,
look up fprintf and sprintf
89
Example of Input and Output
% hello.m greets you and asks for your name.
% It then tells you the date.
disp('Hello! Who are you? ')
name= input ('Enter your name inside quotes ');
d
= date;
greeting= ['Hello ', name, '. Today is ', d, '.'];
disp(greeting)
90
Another example
% simple.m computes product and sum
val1
= input('enter first value: ');
val2
= input('enter second value: ');
prod
= val1*val2;
sum
= val1+val2;
disp(['product is ', num2str(prod)])
disp(['sum is ', num2str(sum)])
91
Checking Correct Password
% Open Sesame
password=input('password please = ');
while password ~= 123456 % 123456=password
disp('Incorrect! Try again.')
password=input('password please = ');
end
disp('Correct! Door’s opening.')
92
Debugging
• If your program has errors (bugs),
MATLAB will tell you the number of
the line where the errors are located
• Any corrections to errors or spelling
mistakes, and changes you want to
make to your program can be done by
clicking back to the Editor Window
• Type corrections over the top of the
program and resave/rerun
93
error location
cursor position
94
• Functions
95
Average of n Random Numbers
Recall that we can use
the script testavg.m to
compute the average of n
random numbers.
%program testavg
How do we input the
number n, and how do
we output the average?
for i = 1:n
a = rand(n,1);
s = 0;
s = s+a(i);
end
avg=s/n
96
Input the Arguments
For m-files, there are
two ways of entering the
input arguments.
%program testavg
Method I:
s = 0;
the input argument n is
enter outside the
program.
for i = 1:n
>> n=1000;
a = rand(n,1);
s = s+a(i);
end
avg=s/n
>> testavg
97
%program testavg
Method II:
n=input('n= ')
we enter the argument n
by the input command.
a = rand(n,1);
>> testavg
for i = 1:n
n=
s = 0;
s = s+a(i);
end
avg=s/n
98
Output the Results
For m-files, there are
two ways to output the
results.
%program testavg
Method I:
for i = 1:n
Result is printed inside
the program by omitting
“;” or using disp.
a = rand(n,1);
s = 0;
s = s+a(i);
end
avg=s/n
>> n=1000;
>> testavg
99
Method II:
the output avg is printed
outside the program by
suppressing output inside
the program using “;”.
>> n=1000;
%program testavg
a = rand(n,1);
s = 0;
for i = 1:n
s = s+a(i);
>> testavg;
end
>> avg
avg=s/n;
100
Functions
Functions simplify the
input and output
process by doing
everything in one line.
Save it also as an m
file, e.g. testavgf.m.
To run, enter
>> testavgf(1000)
or
>> b=testavgf(1000)
output
function
name
input
function avg=testavgf(n)
%testavgf computes the
%average of n numbers
a = rand(n,1);
s = 0;
for i = 1:n
s = s+a(i);
end
avg=s/n;
101
A Function with No Input
function sesame
password=input('password please = ');
while password ~= 123456
disp('Incorrect! Try again.')
password=input('password please = ');
end
disp('Correct! Door opening.')
102
Another Simple Example
function v= Enorm(x)
% Enorm computes the Euclidean norm of x
n=length(x);
sum=0;
for i=1:n
sum= sum+x(i)^2;
end
v=sqrt(sum);
To use it, enter, e.g.
>> Enorm([1 2 3])
103
Script Variables are Global
It is different from
scripts (e.g. testavg)
where the variables
inside the scripts are
the same as any
variables inside or
outside the scripts with
the same name.
>> avg=45;
>> n=2500;
>> testavg;
n=1000
>> avg
avg=
0.5010
>> n
n=
1000
104
Function Variables are Local
All variables (e.g. s,
n, a, avg) inside a
function (testavgf)
live only when the
function is running,
and will be forgotten
when the function
finishes. It will not
affect any variables
outside the function.
>> avg=45;
>> n=2500;
>> testavgf(1000);
>> avg
avg=
45
>> n
n=
2500
Function variables are dummy variables
105
Multiple Inputs
The function “cylvol.m”
r
function vol = cylvol(r,h)
h
basearea = pi*r^2;
vol = basearea*h;
computes the volume of a cylinder. Try
>>cylvol(2,3)
106
Another Example of Multiple Inputs
The projection of x onto y:
x
function u= proj(x,y)
% proj computes the
% projection of x onto y
u
y
u=((x*y')/norm(y)^2)*y;
To use it, enter, e.g.
>> proj([1 2 3],[3 4 5])
107
Multiple Outputs
The following program will return 2 outputs:
function [prod,sum]=simple(val1,val2)
% simple math program
prod
= val1*val2;
sum
= val1+val2;
To use it, enter, e.g.
>> [a,b]=simple(5,6)
108
Another Example of Multiple Outputs
function [i,sum]=sum2N(N)
% sum 1 to n until total > N
sum=0; i=0;
while sum < N
i=i+1;
sum=sum+i;
end
>> [r,c]=sum2N(100)
109
MIMO
The following program computes
the two roots of a quadratic
equations ax2+bx+c=0
function [r1,r2] = quadroot(a,b,c)
r1= (-b-sqrt(b^2-4*a*c))/(2*a);
r2= (-b+sqrt(b^2-4*a*c))/(2*a);
Call by:
>>[xplus,xminus] = quadroot(2,3,4)
110
Comparison between Scripts and Functions
Scripts
Functions
Input
n=input(‘n’=)
fn_name(n)
Output
disp(avg)
avg=fn_name(n)
Multiple inputs
Multiple input lines
fn_name(n, m, p, q)
Multiple outputs
disp([a, b, c, … ])
[a, b, c]=fn_name(n)
Call
>> script_name
>> [a,b,..]=fn_name(m,n,…)
Variables
global
local
variables remain in
memory when program
ends
Variables in function cease to
exist when function ends
(dummy variables)
different programs use
different variable names
different functions use same
variable names is okay
111