1 1 department of mathematics chinese university of hong kong prepared and revised by raymond chan

111
1 1 Department of Mathematics Chinese University of Hong Kong Prepared and revised by Raymond Chan

Upload: erika-campbell

Post on 19-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

1 1

Department of MathematicsChinese University of Hong Kong

Prepared and revised by Raymond Chan

2 2

• What is MATLAB?• MATLAB Demo

3 3

What is MATLAB?

• MATrix LABoratory • Calculator• Interactive• Programming language• Scientific computation and visualization tool• Symbolic computing tool

4 4

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)

5 5

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)

6 6

Mesh plot:

z=peaks(25); mesh(z);

Surface plot: z=peaks(25); surf(z);

Contour plot:

z=peaks(25); contour(z,16); Spherical harmonic: spharm2

3D Graphics

7 7

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

Symbolic Computations

8 8

Command Window:

where you input

MATLAB commands

Directory Window:

show the files in the directory

History Window: record

what you have done

MATLAB DesktopTo start MATLAB: Programs => MATLAB => MATLAB 7.12

Workspace Window:

show what variables

in memory

9 9

• MATLAB as Calculator• Scalar Variables• Vectors and Matrices• Basic Matrix Operations

10

Just enter after the prompt “>>”:

2+2 100-43

3*3 5/2 2^8

log(2)*sin(pi/2)acos(-1)/exp(4)

MATLAB as Calculator

11 11

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, %, ^, +, -, *, /.

12 12

• 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.

MATLAB References

13

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

More general function names can be found at:http://www.mathworks.com/help/matlab/index.html

You can find that by going to :http://www.mathworks.com/help/matlab/ref/arithmeticoperators.html

14

Variables are locations to store values and results. For example, try this: >> x = 2This assigns the value 2 to the variable x.

To see what’s inside x, type: >> x Now try:>> y=4>> x+y

Scalar Variables

15

This: >> z = 3;assigns the value 3 to the variable z withoutprinting it.

You can have variable name like: X, A2, x_y

Cases are sensitive: x is not the same as X

Scalar Variables

16

Three built-in variables are: pi, i, j, where

Not good to re-assign pi as a variable. To reset i:>> clearor>> i = sqrt(-1)

Built-in Variables

pi= ,i,j= -1

17

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

Who’s Who in My Memory

18

How to input:

rvec = [1 2 3] cvec = [4 cvec = [4 3 3 4 4 2] 2] mat = [3 3 4 mat = [ 3 3 4 4 5 6 4 5 6 9 9 0] 9 9 0]

Vectors and Matrices

099

654

433

19

Or simply: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 matrixones(1,4) =[1, 1, 1, 1]eye(4,4) =4-by-4 identity matrixrand(4,1) =4-by-1 random matrix[1:4] =[1, 2, 3, 4][1:0.5:3] =[1, 1.5, 2, 2.5, 3] [3:-0.5:1] =[3, 2.5, 2, 1.5, 1]

[start:stepsize:end]

099

654

433

20

>> x=2.3909302;>> format long; x

2.390930200000000 >> format long e; x

2.390930200000000e+000>> y=239.09302;>> format short e; y

2.3909e+002>> format short; y

239.0930

Controlling Output

Scientific or

Exponential notation

21

>> 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

Controlling Output

8

4

7

3

6

2

5

1

22

quit, exit quit MATLABdiary log the sessionclear clear all variables in the memoryhelp XX help on the command XXwho what variables in memorywhos size of the variableslookfor XY search command related to XYclc clear command window; suppress printing% comments (matlab will not read)

Some Useful Commands

23

C = [3 1 1; 0 2 4 ; -1 0 1] % C is a 3-by-3 matrix d = [2 3 4] % d is a row vectore = d' % e is transpose of dsize(C) % size of Clength(d) % length of d3*C % scalar multiplication C*e % matrix-vector productC*C % matrix-matrix productC\e % solution to C x = ed/C % solution to d = x CC^2 % square of C = C*C

Basic Matrix Operations

24

3.*A = 3*AA + B = A+BA – B = A-BA.*B = ai,j * bi,j

A./B = ai,j / bi,j

A.^2 = ai,j * ai,j

A+3 = ai,j + 3

Entry-wise Operations

25

MATLAB notation Mathematical equivalentRight division: a/b a/bLeft division : a\b b/a Elementary matrix and array operations: Operation Matrix sense Entry-wise sense

Addition + +

Subtraction - -

Multiplication * .*

Left division \ .\

Right division / ./

Exponentiation ^ .^

26

Scalar Functions for Matrices

sin(C) % sine of each entry of matrix Cexp(C) % exponential of each entry of Creal(C) % real part of each entry of C ceil(C) % round each C’s entry upfloor(C) % round each C’s entry downsqrt(C) % square root of each entry of CC^(1/2) % matrix square root of C

27

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

Scalar Functions as Matrix Functions

• Graphics

• 2D Plots

Matlab is a powerful visualization tool. From 2D plots to 3D plots to image processing.

Visualization Tools

contour plot

vector field

image processing

compression

Visualization Tools

3D surface plot

view from different

angles

2D Example: y=sin(x)

x = 0:0.01:pi;

plot(x, sin(x))

[x, y] = meshgrid(-3:0.1:3, -3:0.1:3);

z = x .* y;

mesh(x,y,z);

3D Example: z = x * y

To create a graph you run:

• Management commands:

arranging the figure windows • Graph generation commands:

plot, mesh• Annotation commands:

formatting the graphs

Graphics

Plotting Commands: 3 categories

Management Graphic Annotation

figure plot title

subplot semilogx xlabel, ylabel

zoom semilogy text

hold loglog grid

close polar legend

view fill box

rotate bar 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]))

0 5 1 0 1 5 2 0 2 5 3 0 3 5 4 0 4 5 5 04

4 . 5

5

5 . 5

6

6 . 5

7

7 . 5

8

Example: x=[0:0.1:10];

semilogy(x,exp(x));

0 1 2 3 4 5 6 7 8 9 1 01 0

0

1 01

1 02

1 03

1 04

1 05

Example:t=[0:0.1:10];

polar(t,t);

2

4

6

8

1 0

3 0

2 1 0

6 0

2 4 0

9 0

2 7 0

1 2 0

3 0 0

1 5 0

3 3 0

1 8 0 0

(x,y)=(tcost, tsint)

• 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)

>> 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)

Example:

>> 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--',….)

More Sophisticated Plot:

>> x=0:0.05:pi; >> plot(x,cos(x),'r-',x,sin(x),'mv')

Example:

Colors, Markers and Line Types

Color Marker Liney yellow point solidm magenta circle : dottedc cyan x x-mark .r red + plus dashedg green * star

b blue s square

w white d diamond

k black v triangle (down)

^ triangle (up)

< triangle (left)

> triangle (right)

p pentagram

h hexagram

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

Annotation Commands:

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.'})

Example:

• 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

Managing the Figure Windows

x = 0:0.01:pi;

plot(x, sin(x));

plot(x, cos(x));

Compare:x = 0:0.01:pi;

plot(x, sin(x));

hold

plot(x, cos(x));

• 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

What if you want separate figures?

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));

Example:

52

• Matrix Functions • Matrix Inverse

1. inv 2. \3. rref

• Determinant• Norm

53

inv(C) % inverse of matrix Cdet(C) % determinant of Ceig(C) % eigenvalues of C[V,D]=eig(C) % e-value and e-vector of Cnorm(C) % norm of C diag(C) % diagonal part of Crank(C) % rank of Cpinv(C) % pseudoinverse of Csum(C) % column sum of Ccross(d,e) % cross product of d and e

Matrix Functions

54

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

55

If A is not invertible, then

*

*

*

*

*

*****

****

*

*

*

*

***

***

***

****

*

**001

*

*

1

01

0

Bk · · · B1

Reduced Row Echelon Form

It can be obtained in MATLAB by

>> rref(A)

56

For examples

rref

1087

654

321

100

010

001

rref

987

654

321

000

210

-101

19

14

9

4

20

15

10

5

181716

131211

876

321

rref

0

0

3

-2

0

0

4

-3

000

000

210

-101

rank = 2

rank = 3

rank = 2

Given A = [aij]

n

jijij

ji MaA1

)det()1()det(

n

iijij

ji Ma1

)det()1(

where Mij is the submatrix obtained by deleting row i and column j.

Why compute det(A)?

det(A) = 0 A is singular

Determinant

58

Logical Flow

• Relation and logical operators• Controlling statements: for, while and if

59

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

60

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

61

Control Statements MATLAB has three control constructs:

for, while, if for is an iterated loop statement

for i = 1:n… % loop body statements

… % every

statement here is … % repeated n times

end or

for i = m:s:n … % from m to n in steps of s

end

62

% to compute the sum from 1 to 10

sum = 0;

for i = 1:10

sum=sum+i;

end

% this can also be done by sum(1:10)

Example: for

for i-loop

63

% to compute the factorial of 10

fact = 1;

for i = 2:10

fact = fact*i;

end

% this can also be done by factorial(10);

Example: for

64

% 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);

Example: for

65

% 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)

Example: for

66

% to generate a k-by-k Hilbert matrix

k=5;

A = zeros(k,k);

for m = 1:k

for n = 1:k

A(m,n) = 1/(m+n -1);

end % for n - loop

end % for m - loop

A

Example: Nesting for-loopNesting refers to the act of putting a for-loop within a for-loop

)12/(1)22/(1

)22/(1

3/1

3/12/1

3/12/11

nn

n

67

% Matrix multiplication C = A*B

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 - loopend % for m - loop

Example: Nesting for-loop

k

j

knmnjBjmAnmC1

.,1),,(),(),(

68

While Control

while construct:

while <condition> … % every statements

here… % will be repeated

until… % condition is not

satisfiedend

69

% sum a random vector a = rand(1,100); s = 0; j=1; % set the test variablewhile j < 101

s = s+a(j); j = j+1; % update test variable

end

Example: while

% 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

70

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

71

% 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 numberend

Sum rand until rand < 0.9

72

if construct:

if <condition>… % do this if condition is

trueelse

… % do that otherwise(elseif <condition>)

(…) % you can have more conditions

end

If Control

73

if A > B

disp('A is larger')

elseif A < B

disp('B is larger')

elseif A == B

disp('A equals B')

else disp('Unexpected situation')

end

Example: if/elseif/else

if A > B

disp('A is larger')

else disp('A is not larger')

end

74

% 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

Example: if/elseif/else

75

• Programs

• Scripts

76

Why programs

a = rand(1000,1);

s = 0;

for i = 1:1000

s = s+a(i);

end

s/1000

When we want to do something repeatedly.

Suppose we want to see if the average of 1,000 uniformly-distributed random numbers is close to 0.5.

What if we want to run this several times?

77

• 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.

78

• 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.

To create a MATLAB script

79

Command Window

Editor Window

Enter your program here

80

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.

81

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.

To Run a Script:

82

• 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.

Advantage of Writing Programs

83

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

84

% a program called multiply.m% take two variables and multiply them

a = 5 ;

b = 3 ;

product = a * b

An Example of MATLAB Program

Type this into your editor, save it with the name “multiply.m” and ‘run’ it with the command

>> multiply

85

Sometimes we want to change the results of the program by changing some of the input variables.

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.

Input the Arguments

n=input('n= ')

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

s/n

86

% a program called multiply.m% take two variables and multiply them

a=input('a= ')

b=input('b= ')

product = a * b

A Simple Program with 2 Inputs

Type this into your editor, save it with the name “multiply.m” and ‘run’ it with the command

>> multiply

87

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? 

To sketch a surface :

88

First is to print them without the “;”

% a simple program

a = 7;

b = 3;

c = a+b;

c

 the result of c is presented. 

Output the Results

89

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

90

% 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)

Example of Input and Output

91

% 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)])

Another example

92

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.')

93

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

94

error location

cursor position

95

• Functions

96

Recall that we can use the script testavg.m to compute the average of n random numbers.

How do we input the number n, and how do we output the average?

Average of n Random Numbers

%program testavg

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

avg=s/n

97

For m-files, there are two ways of entering the input arguments.

Method I:

the input argument n is enter outside the program.

>> n=1000;

>> testavg

Input the Arguments

%program testavg

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

avg=s/n

98

Method II:

we enter the argument n by the input command.

>> testavg

n=

%program testavg

n=input('n= ')

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

avg=s/n

99

Method I:

Result is printed inside the program by omitting “;” or using disp.

>> n=1000;

>> testavg

%program testavg

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

avg=s/n

Output the ResultsFor m-files, there are two ways to output the results.

100

Method II:

the output avg is printed outside the program by suppressing output inside the program using “;”.

>> n=1000;

>> testavg;

>> avg

%program testavg

a = rand(n,1);

s = 0;

for i = 1:n

s = s+a(i);

end

avg=s/n;

101

Functions simplify the input and output process by doing everything in one line.

Functions

Save it also as an m file, e.g. testavgf.m.

To run, enter

>> testavgf(1000)

or

>> b=testavgf(1000)

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;

inputoutputfunction

name

102

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.')

103

Another Simple Example

function v= Enorm(x)% Enorm computes the Euclidean norm of xn=length(x);sum=0;for i=1:n

sum= sum+x(i)^2;endv=sqrt(sum);

 To use it, enter, e.g.

>> Enorm([1 2 3])

104

Script Variables are Global

>> avg=45;>> n=2500;>> testavg;n=1000>> avgavg= 0.5010>> nn = 1000

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.

105

Function Variables are Local

>> avg=45;>> n=2500;>> testavgf(1000);>> avgavg= 45 >> nn= 2500

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.

Function variables are dummy variables

106

The function “cylvol.m”

function vol = cylvol(r,h)

basearea = pi*r^2;

vol = basearea*h;

computes the volume of a cylinder. Try

>>cylvol(2,3)

 

Multiple Inputs

r

h

107

Another Example of Multiple Inputs

function u= proj(x,y)

% proj computes the

% projection of x onto y

u=((x*y')/norm(y)^2)*y;

To use it, enter, e.g.

>> proj([1 2 3],[3 4 5])

x

yu

The projection of x onto y:

108

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)

109

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)

110

Call by:>>[xplus,xminus] = quadroot(2,3,4)

MIMO

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);

The following program computes the two roots of a quadratic equations ax2+bx+c=0

111

Comparison between Scripts and FunctionsScripts 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