introduction to matlab zongqiang liao research computing group unc-chapel hill

79
Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

Upload: jacob-morton

Post on 27-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

Introduction to MATLABIntroduction to MATLAB

Zongqiang LiaoResearch Computing Group

UNC-Chapel Hill

Page 2: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 2

Course outlineCourse outline

Introduction

Getting started

Mathematical functions

Matrix generation

Matrix and array operations

Reading and writing data files

Basic plotting

Basic programming

Page 3: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

IntroductionIntroduction

Page 4: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 4

IntroductionIntroduction

The name MATLAB stands for MATrix LABoratoryIt is good at dealing with matrices

Vendor’s website: http//:www.mathworks.com

Advantages of MATLABEasiness of use

Powerful build-in routines and toolboxes

Good visualization of results

Disadvantage of MATLABCan be slow

Page 5: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Getting startedGetting started

Page 6: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 6

Getting startedGetting started

MATLAB desktopThe Command Window

The Command History

The Workspace

The Current Directory

The Help Browser

The Start Button

Page 7: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 7

Getting startedGetting started

Keeping track of your work sessiondiary command

>> diary

or

>> diary FileName

Stop the recording

>> diary off

Start the recording again

>>diary on

Page 8: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 8

Getting startedGetting started

Using MATLAB as a calculator>> 1+2*3

ans =

7

You may assign the value to a output variable

>> x=1+2*3

x=

7

x can be used in the some calculation later

>> 4*x

ans =

28

Page 9: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 9

Getting startedGetting started

Suppressing outputYou can suppress the numerical output by putting a

semicolon (;) at the end of the line

>> t=-13;

We can place several statements on one line, separated by commas (,) or semicolons(;)

>> t=-13; u=5*t, v=t^2+u

u=

-65

v=

104

Page 10: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 10

Getting startedGetting started

Managing the workspaceThe results of one problem may have an effect on

the next one

Issue a clear command at the start of each new independent calculation

>> clear

or

>> clear all

Page 11: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 11

Getting startedGetting started

Miscellaneous commandsTo clear the Command Window

>> clc

To abort a MATLAB computation

ctrl-C

To continue a line

Page 12: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 12

Getting startedGetting started

Getting helpUse help to request info on a specific function

>> help sqrt

Use doc function to open the on-line version of the help menu

>> doc plot

Use lookfor to find function by keywords

>> lookfor functionkeyword

Page 13: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Mathematical functionsMathematical functions

Page 14: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 14

Mathematical functions

Mathematical functions

Lists of build-in mathematical functionsElementary functions

>> help elfun

Special functions

>> help specfun

Such as

sin(x), cos(x), tan(x), ex, ln(x)

Page 15: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 15

Mathematical functions

Mathematical functions

Example 1

Calculate z=e-asin(x)+10 for a=5, x=2, y=8

>> a=5; x=2; y=8;

>> z=exp(-a)*sin(x)+10*sqrt(y)

z=

28.2904

y

Page 16: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 16

Mathematical functions

Mathematical functions

Example 2

Calculate the roots of a equation

ax2+bx+c=0, for a=2, b=1, and c=-4

>> a=2; b=1; c=-4;

>> x1=(-b+sqrt(b^2-4*a*c))/(2*a)

x1=

1.1861

>> x2=(-b-sqrt(b^2-4*a*c))/(2*a)

x2=

-1.1861

Page 17: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 17

Mathematical functions

Mathematical functions

Example 3

>> log(142)

ans=

4.9558

>> log10(142)

ans=

2.1523

Page 18: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 18

Mathematical functions

Mathematical functions

Example 4

Calculate sin( /4)

>> sin(pi/4)

ans =

0.7071

Calculate e10

>> exp(10)

ans =

2.2026e+004

Page 19: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Matrix generationMatrix generation

Page 20: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 20

Matrix generationMatrix generation

The name MATLAB is taken from ”MATrix LABoratory.” It is good at dealing with matrices.

Actually all variables in MATLAB are matrices. Scalars are 1-by-1 matrices

vectors are N-by-1 (or 1-by-N) matrices.

You can see this by executing

>> size(x)

Page 21: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 21

Matrix generationMatrix generation

Entering a matrix

Begin with a square bracket, [

Separate elements in a row with spaces or commas (,)

Use a semicolon (;) to separate rows

End the matrix with another square bracket, ]

Page 22: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 22

Matrix generationMatrix generation

• Entering a matrix: A typical example

>> A=[1 2 3; 4 5 6; 7 8 9]

>> A=

1 2 3

4 5 6

7 8 9

Page 23: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 23

Matrix generationMatrix generation

Matrix indexing

View a particular element in a matrix

For example, A(1,3) is an element of first row and third column

>>A(1,3)

>>ans =

3

Page 24: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 24

Matrix generationMatrix generation

Colon operator in a matrix

Colon operator is very useful in the usage of MATLAB

For example, A(m:n,k:l) specifies portions of a matrix A: rows m to n and column k to l.

Page 25: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 25

Matrix generationMatrix generation

Colon operator in a matrix

Example 1

Rows 2 and 3 and columns 2 and 3 of matrix A

>>A(2:3, 2:3)

ans =

5 6

8 9

Page 26: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 26

Matrix generationMatrix generation

Colon operator in a matrix

Example 2

Second row element of matrix A

>>A(2, :)

ans =

4 5 6

Page 27: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 27

Matrix generationMatrix generation

Colon operator in a matrix

Example 3

Last two columns of matrix A

>>A(:, 2:3)

ans =

2 3

5 6

8 9

Page 28: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 28

Matrix generationMatrix generation

Colon operator in a matrix

Example 4

Last rows of matrix A

>>A(2:end, :)

ans =

4 5 6

7 8 9

The end here denotes the last index in the specified dimension

Page 29: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 29

Matrix generationMatrix generation

Transposing a matrix

The transposing operation is a single quote (’)

>>A’

ans =

1 4 7

2 5 8

3 6 9

Page 30: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 30

Matrix generationMatrix generation

Concatenating matrices

Matrices can be made up of sub-matrices

>>B= [A 10*A; -A [1 0 0; 0 1 0; 0 0 1]]

B =

1 2 3 10 20 30

4 5 6 40 50 60

7 8 9 70 80 90

-1 -2 -3 1 0 0

-4 -5 -6 0 1 0

-7 -8 -9 0 0 1

Page 31: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 31

Matrix generationMatrix generation

Generating vectors: colon operator

Suppose we want to enter a vector x consisting of points (0, 0.1, 0.2, 0.3,…,5)

>>x=0:0.1:5;

All the elements in between 0 and 5 increase by one-tenth

Page 32: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 32

Matrix generationMatrix generation

Generating vectors: linear spacing

Suppose we want to have direct control over the number of points.

>>y=linspace(a, b, n)

For example,

>>theta=linspace(0, 2*pi, 101)

Creates a vector of 101 elements in the interval

Page 33: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 33

Matrix generationMatrix generation

Elementary matrix generatorseye(m,n)

eye(n)

zeros(m,n)

ones(m,n)

diag(A)

rand(m,n)

randn(m,n)

logspace(a,b,n)

For a complete list of elementary matrices

>>help elmat

>>doc elmat

Page 34: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Matrix arithmetic operationMatrix arithmetic operation

Page 35: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 35

Matrix arithmetic operation

Matrix arithmetic operation

Arithmetic operations

A+B or B+A

A*B

A^2 or A*A

a*A or A*a

Page 36: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 36

Matrix arithmetic operation

Matrix arithmetic operation

Matrix functions

det

diag

eig

inv

norm

rank

Page 37: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 37

Matrix arithmetic operation

Matrix arithmetic operation

Matrix functionsFor example

>> A=[1 2 3; 4 5 6; 7 8 0];

>>inv(A)

ans =

-1.7778 0.8889 -0.1111

1.5556 -0.7778 0.2222

-0.1111 0.2222 -0.1111

>>det(A)

ans =

27

Page 38: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 38

Matrix arithmetic operation

Matrix arithmetic operation

More matrix operations

Calculate the sum of elements in the second row of matrix A

>> sum(A(2,:))

Calculates the sum of the last column of A

>>sum(A(:,end))

Page 39: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Array arithmetic operationArray arithmetic operation

Page 40: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 40

Array arithmetic operation

Array arithmetic operation

Array operations

Array operations are done element-by-element

The period character (.) is used in array operations

The matrix and array operations are the same for addition (+) and subtraction (-)

Page 41: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 41

Array arithmetic operation

Array arithmetic operation

Array operations

If A and B are two matrices of the same size with elements A=[aij] and B=[bij]

C=A.*B produces a matrix C of the same size with elements cij = aijbij

C=A./B produces a matrix C of the same size with elements cij = aij/bij

C=A.^2 produces a matrix C of the same size with elements cij = aij

2

Page 42: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 42

Array arithmetic operation

Array arithmetic operation

Array operationsExample 1

A= B=

>>C=A.*B

C=

10 40 90

160 250 360

490 640 810

987

654

321

908070

605040

302010

Page 43: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 43

Array arithmetic operation

Array arithmetic operation

Array operations

Example 2

>>C=A.^2

C=

1 4 9

16 25 36

49 64 81

Page 44: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Reading and writing data files

Reading and writing data files

Page 45: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 45

Reading and writing data files

Reading and writing data files

Save and load data file

Use command save to save the variable in the workspace

For example, use command save:

>> x = [1 3 -4];

>> y = [2 -1 7];

>> z = [3 2 3];

>> save Filename.mat

The command saves all variables in the workspace

into a binary file Filename.mat

Page 46: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 46

Reading and writing data files

Reading and writing data files

Save and load data file

Save only certain variables by specifying the variable names after the file name

>> save Filename.mat x y

Save variables into ASCII data file

>> save Filename.dat x y –ascii

Page 47: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 47

Reading and writing data files

Reading and writing data files

Save and load data file

The data can be read back with the load command

>> load Filename.mat

Load only some of the variables into memory

>> load Filename.mat x

Load the ASCII data file back into memory

>> load Filename.dat -ascii

Page 48: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 48

Reading and writing data files

Reading and writing data files

The textread function

The load command assumes all of data is of a single type

The textread function is more flexible, it is designed to read ASCII files where each column can be of a different type

The command is:

>> [A,B,C,...] = textread(filename, format, n);

Page 49: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 49

Reading and writing data files

Reading and writing data files

The textread function

For example, if a text file “mydata.dat” contains the following lines:

tommy 32 male 78.8

sandy 3 female 88.2

alex 27 male 44.4

saul 11 male 99.6

The command is:>> [name,age,gender,score] = textread(‘mydata.dat’, ‘%s %d %s %f’, 4);

Page 50: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 50

Reading and writing data files

Reading and writing data files

C style read/write

MATLAB allows C style file access. It is crucially important that a correct data format is used.

The steps are:

Open a file for reading or writing. A unique file identifier is assigned.

Read the data to a vector

Close the file with file identifier

Page 51: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 51

Reading and writing data files

Reading and writing data files

C style read/write: formatted files

In order to read results in formatted data files, the data format of the files must be know

For example, the numeric data is store in a file ‘sound.dat’. The commands reading data are:

>> fid = fopen(‘sound.dat’,‘r’);

>> data = fscanf(fid, ‘%f’);

>> fclose(fid);

Page 52: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 52

Reading and writing data files

Reading and writing data files

C style read/write: unformatted/binary files

In order to read results in unformatted data files, the data precision of the files must be specified

For example, the numeric data is store as floating point numbers using 32 memory bits in a file ‘vib.dat’. The commands reading data are:

>> fid1 = fopen(‘vib.dat’,‘rb’);

>> data = fread(fid1, ‘float32’);

>> fclose(fid);

Page 53: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Basic plottingBasic plotting

Page 54: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 54

Basic plottingBasic plotting

Plotting elementary functions

To plot the function y=sin(x) on the interval

[0, 2 ]

First create a vector of x values ranging from 0 to 2

Compute the sine of these values

Plot the result

Page 55: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 55

Basic plottingBasic plotting

Plotting elementary functions

>>x=0:pi/100:2*pi;

>>y=sin(x);

>>plot(x,y)

Page 56: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 56

Basic plottingBasic plotting

Plotting elementary functions

Page 57: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 57

Basic plottingBasic plotting

Adding titles, axis labels

>>xlabel (‘x=0:2\pi’);

>>ylabel (‘Sine of x’);

>>title (‘Plot of the Sine function’);

The character \pi creates the symbol

Page 58: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 58

Basic plottingBasic plotting

Multiple data sets in one plot

Several graphs may be drawn on the same figure

For example, plot three related function of x: y1=2cos(x), y2=cos(x), and y3=0.5cos(x), on the interval [0, 2 ]

Page 59: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 59

Basic plottingBasic plotting

Multiple data sets in one plot

>> x = 0:pi/100:2*pi;

>> y1 = 2*cos(x);

>> y2 = cos(x);

>> y3 = 0.5*cos(x);

>> plot(x,y1,‘--’,x,y2,‘-’,x,y3,‘:’)

>> xlabel(‘0 \leq x \leq 2\pi’)

>> ylabel(‘Cosine functions’)

>> legend(‘2*cos(x)’,‘cos(x)’,‘0.5*cos(x)’)

>> title(‘Typical example of multiple plots’)

Page 60: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 60

Basic plottingBasic plotting

Multiple data sets in one plot

Page 61: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 61

Basic plottingBasic plotting

Subplot

The graphic window can be split into an m*n array of small windows.

The windows are counted 1 to mn row-wise, starting from the top left

For example, plot three related function of x: y1=sin(3 x), y2=cos(3 x), y3=sin(6 x), y4=cos(6 x), on the interval [0, 1]

Page 62: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 62

Basic plottingBasic plotting

Subplot>> x = 0:1/100:1;

>> y1 = sin(3*pi*x);

>> y2 = cos(3*pi*x);

>> y3 = sin(6*pi*x);

>> y4 = cos(6*pi*x);

>> title(‘Typical example of subplots’)

>> subplot(2,2,1), plot(x,y1)

>> xlabel(‘0 \leq x \leq 1’), ylabel(‘sin(3 \pi x)’)

>> subplot(2,2,2), plot(x,y2)

>> xlabel(‘0 \leq x \leq 1’), ylabel(‘cos(3 \pi x)’)

>> subplot(2,2,3), plot(x,y3)

>> xlabel(‘0 \leq x \leq 1’), ylabel(‘sin(6 \pi x)’)

>> subplot(2,2,4), plot(x,y4)

>> xlabel(‘0 \leq x \leq 1’), ylabel(‘cos(6 \pi x)’)

Page 63: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 63

Basic plottingBasic plotting

Subplot

Page 64: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Programming in MATLABProgramming in MATLAB

Page 65: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 65

Programming in MATLAB

Programming in MATLAB

M-File scripts

In order to repeat any calculation and/or make any adjustments, it is create a file with a list of commands.

“File New M-file”

For example, put the commands for calculating the roots of a quadratic equation into a file called quat.m

Page 66: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 66

Programming in MATLAB

Programming in MATLAB

M-File scripts

Enter the following statements in the filea = 2;

b = 1;

c = -4;

x1=(-b+sqrt(b^2-4*a*c))/(2*a)

x2=(-b-sqrt(b^2-4*a*c))/(2*a)

Save and name the file, quat.m

Note: the first character of the filename must be a letter

Page 67: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 67

Programming in MATLAB

Programming in MATLAB

M-File scripts

Run the file

>> quat

x1=

1.1861

x2=

-1.1861

Page 68: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 68

Programming in MATLAB

Programming in MATLAB

M-File scripts

It is possible to modify the file so that it prompts you for inputting values of a, b, and c each time it runs.

a = input(‘Enter a: ’);

b = input(‘Enter b: ’);

c = input(‘Enter c: ’);

x1=(-b+sqrt(b^2-4*a*c))/(2*a)

x2=(-b-sqrt(b^2-4*a*c))/(2*a)

Page 69: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 69

Programming in MATLAB

Programming in MATLAB

M-File scriptsRe-run this file, you may type in the values for a, b

and c

>> quat

Enter a: 3

Enter b: 4

Enter c: 5

x1 =

-0.6667 + 1.1055i

x2 =

-0.6667 - 1.1055i

Page 70: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 70

Programming in MATLAB

Programming in MATLAB

M-File scriptsMATLAB treats anything that appears after the % on

a line as comments and these line will be ignored when the file runs

% -------------------------------------------------------

% quat.m is to solve quadratic equation ax^2 + bx + c =0

% -------------------------------------------------------

a = input(‘Enter a: ’);

b = input(‘Enter b: ’);

c = input(‘Enter c: ’);

x1=(-b+sqrt(b^2-4*a*c))/(2*a)

x2=(-b-sqrt(b^2-4*a*c))/(2*a)

Page 71: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 71

Programming in MATLAB

Programming in MATLAB

M-File scripts

You can display the first block of comment lines in any .m file by issuing the help command

>>help quat

% -------------------------------------------------------

% quat.m is to solve quadratic equation ax^2 + bx + c =0

% -------------------------------------------------------

Page 72: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 72

Programming in MATLAB

Programming in MATLAB

M-File functionsFunctions are routines that are general and applicable

to many problems.

To define a MATLAB function:Decide a name for the function, making sure that it

does not conflict a name that is already used by MATLAB.

Document the function

The first command line of the file must have this format:

Function[list of outputs]=functionname(list of inputs)

…….

Save the function as a M-file

Page 73: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 73

Programming in MATLAB

Programming in MATLAB

M-File scriptsIn the previous example, it is convenient to have a

separate file which calculate the roots of a quadratic equation

% -------------------------------------------------------

% quatsolv.m is to compute the roots of quadratic

% equation ax^2 + bx + c =0

% -------------------------------------------------------

function [x1, x2] = quatsolv(a, b, c)

x1=(-b+sqrt(b^2-4*a*c))/(2*a)

x2=(-b-sqrt(b^2-4*a*c))/(2*a)

Page 74: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 74

Programming in MATLAB

Programming in MATLAB

M-File scriptsTo evaluate this function, a main program is needed. This

main program provides input argumentss (a, b, and c)

% -------------------------------------------------------

% main.m is to solve quadratic equation ax^2 + bx + c =0

% it calls the external function quatsolv.m

% -------------------------------------------------------

a = input(‘Enter a: ’);

b = input(‘Enter b: ’);

c = input(‘Enter c: ’);

[x1, x2] = quatsolv(a, b, c);

x1

x2

Page 75: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 75

Programming in MATLAB

Programming in MATLAB

M-File scripts

Example 2:

A new quatsolv2.m file is defined as the following:

% ----------------------------------------------------------

% quatsolv2.m is to compute the values of

% quadratic equation ax^2 + bx + c

% ----------------------------------------------------------

function y = quatsolv2(x)

global a b c

y = a*x^2 + b*x + c;

Page 76: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 76

Programming in MATLAB

Programming in MATLAB

M-File scriptsExample 2:

A new main file% -------------------------------------------------------

% main2.m is to plot quadratic equation ax^2 + bx + c for

% some range.

% it calls the external function quatsolv2.m

% -------------------------------------------------------

global a b c

a = 1;

b = 0;

c = -2;

fplot(‘quatsolv2’,[-4, 4])

Page 77: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 77

Programming in MATLAB

Programming in MATLAB

M-File scripts If run main2.m

Page 78: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu

Questions and comments?Questions and comments?

Page 79: Introduction to MATLAB Zongqiang Liao Research Computing Group UNC-Chapel Hill

its.unc.edu 79

Questions and comments?

Questions and comments?

For assistance with MATLAB, please contact the Research Computing Group:

Email: [email protected]

Phone: 919-962-HELP

Submit help ticket at http://help.unc.edu