introduction to matlab lecture 2b 9/28/2007 presented to the course it2015 – engineering...

45
Introduction to Introduction to MATLAB MATLAB Lecture 2b Lecture 2b 9/28/2007 9/28/2007 Presented to the course Presented to the course IT2015 – Engineering IT2015 – Engineering Mathematics. Mathematics.

Upload: gervais-charles

Post on 12-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Introduction to Introduction to MATLABMATLAB

Lecture 2bLecture 2b

9/28/20079/28/2007Presented to the course Presented to the course

IT2015 – Engineering IT2015 – Engineering Mathematics.Mathematics.

Page 2: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB is a widely used software for MATLAB is a widely used software for working with matrices.working with matrices.

Many schools are now using this Many schools are now using this software, and numerous workshops software, and numerous workshops have been given on its integration to have been given on its integration to many courses, including linear algebra.many courses, including linear algebra.

In this course we’d like to give you a In this course we’d like to give you a very basic knowledge of using MATLAB very basic knowledge of using MATLAB in dealing with various topics associated in dealing with various topics associated with differential equations.with differential equations.

Page 3: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

What is MATLAB?What is MATLAB?

Product of “The MathWorks, Inc.” locProduct of “The MathWorks, Inc.” located near Boston, MA, U.S.A. since 1984.ated near Boston, MA, U.S.A. since 1984.

Current version installed at CSIE lab is Current version installed at CSIE lab is MATLAB 7.0.1 (Release 14SP1).MATLAB 7.0.1 (Release 14SP1).

MATLAB = MATLAB = MatMatrix rix LabLaboratoryoratory.. MATLAB products are generally divided MATLAB products are generally divided

into “MATLAB” (cores) and “MATLAinto “MATLAB” (cores) and “MATLAB Toolbox”.B Toolbox”.

Page 4: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB product lineMATLAB product line

MATLABMATLAB ((交談式科技計算語言交談式科技計算語言 ) NT 30,000.) NT 30,000. MATLAB COM Builder (COMMATLAB COM Builder (COM 物件工具箱物件工具箱 )) MATLAB Compiler (MATLAB Compiler ( 編譯器編譯器 )) MATLAB Report Generator (MATLABMATLAB Report Generator (MATLAB 報告產生報告產生器器 ))

MATLAB Web Server (MATLAB Web Server ( 網頁結合工具箱網頁結合工具箱 )) MATLAB Runtime Server (MATLAB Runtime Server ( 獨立程式開發工具箱獨立程式開發工具箱 )) MATLAB Excel Builder (ExcelMATLAB Excel Builder (Excel 增益集工具箱增益集工具箱 )) Excel Link (for PC) (ExcelExcel Link (for PC) (Excel 連結工具箱連結工具箱 ))

Page 5: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Toolbox - 1MATLAB Toolbox - 1 <<數學分析應用數學分析應用 >>

Curve Fitting Toolbox (Curve Fitting Toolbox (曲線契合工具箱曲線契合工具箱 )) Optimization Toolbox (Optimization Toolbox (最佳化工具箱最佳化工具箱 )) Statistics Toolbox (Statistics Toolbox (統計工具箱統計工具箱 ) NT 12,000.) NT 12,000. Bioinformatics Toolbox (Bioinformatics Toolbox (生物資訊工具箱生物資訊工具箱 ) NT$ 12,000.) NT$ 12,000. Neural Network Toolbox (Neural Network Toolbox (類神經網路工具箱類神經網路工具箱 )) Symbolic/Extended Symbolic Math Toolbox (Symbolic/Extended Symbolic Math Toolbox ( 符號運符號運算算 //延伸符號運算工具箱延伸符號運算工具箱 ))

Partial Differential Equation Toolbox (Partial Differential Equation Toolbox (偏微分工具箱偏微分工具箱 )) Mapping Toolbox (Mapping Toolbox (地圖工具箱地圖工具箱 )) Spline Toolbox (Spline Toolbox (雲線函數工具箱雲線函數工具箱 ))

Page 6: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Toolbox - 2MATLAB Toolbox - 2 <<資料擷取及匯入資料擷取及匯入 >>

Data Acquisition Toolbox (Data Acquisition Toolbox ( 資料擷取工具箱資料擷取工具箱 )) Instrument Control Toolbox (Instrument Control Toolbox ( 儀器設備控制工具箱儀器設備控制工具箱 )) Image Acquisition Toolbox (Image Acquisition Toolbox ( 影像擷取工具箱影像擷取工具箱 )) Database Toolbox (Database Toolbox ( 資料庫連結工具箱資料庫連結工具箱 ))

<<財務模型及分析財務模型及分析 >> Financial Toolbox (Financial Toolbox ( 財經工具箱財經工具箱 )) Financial Time Series Toolbox (Financial Time Series Toolbox ( 財務時間序列工具箱財務時間序列工具箱 )) GARCH Toolbox (GARCH Toolbox ( 異質條件變異數自我迴歸工具箱異質條件變異數自我迴歸工具箱 )) Financial Derivatives Toolbox (Financial Derivatives Toolbox ( 衍生性金融商品工具衍生性金融商品工具箱箱 ))

Datafeed Toolbox (Datafeed Toolbox ( 財務資料來源工具箱財務資料來源工具箱 )) Fixed-Income Toolbox (Fixed-Income Toolbox ( 固定收益商品工具箱固定收益商品工具箱 ))

Page 7: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Toolbox - 3MATLAB Toolbox - 3

<<信號及影像處理信號及影像處理 >> Signal Processing Toolbox (Signal Processing Toolbox ( 信號處理工具箱信號處理工具箱 )) Image Processing Toolbox (Image Processing Toolbox ( 影像處理工具箱影像處理工具箱 )) Communications Suite (Communications Suite ( 通訊工具組合通訊工具組合 ) ) 包含包含

Communications ToolboxCommunications Toolbox & & BlocksetBlockset System Identification Toolbox (System Identification Toolbox ( 系統辨識工具箱系統辨識工具箱 )) Wavelet Toolbox (Wavelet Toolbox ( 小波工具箱小波工具箱 )) Filter Design Toolbox (Filter Design Toolbox ( 濾波器設計工具箱濾波器設計工具箱 ) ) MATLAB Link for Code Composer Studio™ DevMATLAB Link for Code Composer Studio™ Dev

elopment Tools (MATLABelopment Tools (MATLAB 與與 CCSCCS連結工具箱連結工具箱 ))

Page 8: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Toolbox - 4MATLAB Toolbox - 4

<<控制設計控制設計 >> Control System Toolbox (Control System Toolbox ( 控制系統工具箱控制系統工具箱 )) Fuzzy Logic Toolbox (Fuzzy Logic Toolbox ( 模糊邏輯工具箱模糊邏輯工具箱 )) Robust Control Toolbox (Robust Control Toolbox ( 強韌控制工具箱強韌控制工具箱 )) Mu-Analysis & Synthesis Toolbox (MuMu-Analysis & Synthesis Toolbox (Mu 分析及合成分析及合成工具箱工具箱 ))

LMI Control Toolbox (LMI Control Toolbox ( 線性矩陣不等式控制工具箱線性矩陣不等式控制工具箱 )) Model Predictive Control Toolbox (Model Predictive Control Toolbox ( 模型預測控制工模型預測控制工具箱具箱 ))

Model-Based Calibration Toolbox (Model-basedModel-Based Calibration Toolbox (Model-based 調調校工具箱校工具箱 ))

Page 9: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Running MATLABRunning MATLAB

MATLAB is installed to every PC in MATLAB is installed to every PC in two CSIE computer labs. two CSIE computer labs.

Each time one runs MATLAB, the Each time one runs MATLAB, the license serverlicense server is contacted and is contacted and assigns a license to the client (if assigns a license to the client (if there is any left). We have a total of there is any left). We have a total of 50 licenses available.50 licenses available.

Page 10: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Here is a message that gets displayed if there is some error in obtaining a license from the server.

Page 11: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics
Page 12: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics
Page 13: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Click on links to open the PDF. Be patient, cause it takes some time in getting them through.

Page 14: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics
Page 15: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

1. MATLAB 1. MATLAB BasicsBasics

Page 16: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Renaissance engraving Melencolia I by the German artist and amateur mathematician Albrecht Dürer. This matrix is known as a magic square and was believed by many in Dürer’s time to have genuinely magical properties.

Row 1, 2, 3 and 4 Colu

mn

1, 2

, 3 a

nd

4

Page 17: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

a11a12 a13a14

a21a22 a23a24

a31a32 a33a34

a41a42 a43a44

aij = the element at i-th row and j-th column.

Page 18: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

A few basic conventions: Separate the elements of a row with blanks or

commas. Use a semicolon “ ; “ to indicate the end of each row. Surround the entire list of elements with square

brackets, [ ]. To enter the magic matrix as shown, simply type

in the Command Window: A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

MATLAB displays the matrix you just entered: A =

16 3 2 135 10 11 89 6 7 124 15 14 1

Matrix BasicsMatrix Basics

Note that MATLAB always echoes the value for the most recent variable processed, if you did not postfix “;” at the end of line.

Page 19: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

The first statement to try is “sum(A)”. MATLAB replies with ans =

34 34 34 34 When you do not specify an output variable,

MATLAB uses the variable ans, short for answer, to store the results of a calculation.

You have computed a row vector containing the sums of the columns of A.

Sure enough, each of the columns has the same sum, the magic sum, 34.

The sum of a row vector is straightforward. The sum of a row vector is straightforward. Try to get the sum of a row vector x = (1, 2, 3).Try to get the sum of a row vector x = (1, 2, 3).

Page 20: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

The Colon OperatorThe Colon Operator The colon, :, is one of the most The colon, :, is one of the most

important MATLAB operators. important MATLAB operators. It occurs in several different forms. The expression “1:10” is a row vector

containing the integers from 1 to 10:1 2 3 4 5 6 7 8 9 10

To obtain non-unit spacing, specify an increment. For example, “100:-7:50” is

100 93 86 79 72 65 58 51and “0:pi/4:pi” is

0 0.7854 1.5708 2.3562 3.1416

Page 21: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Subscript expressions involving colons refer to portions of a matrix: A(1:k, j) is the first k elements of the jth column of A. So “sum(A(1:4,4))” computes the sum of the elements from row 1 to row 4 on the fourth column.

But there is a better way. The colon by itself refers to all the elements in a row or column of a matrix and the keyword “end” refers to the last row or column.

So “sum(A(:,end))” computes the sum of the elements in the last column of A.

Page 22: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

The magic functionThe magic function MATLAB actually has a built-in function that create

s magic squares of almost any size. Not surprisingly, this function is named magic:

B = magic(4)B =16 2 3 135 11 10 89 7 6 124 14 15 1

This matrix is almost the same as the one in the Dürer engraving and has all the same “magic” properties; the only difference is that the two middle columns are exchanged.

To make this B into Dürer’s A, swap the two middle columns by the command “A = B(:,[1 3 2 4])”

Page 23: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

VariablesVariables

MATLAB does not require any type declarations or dimension statements. When MATLAB encounters a new variable name, it automatically creates the variable and allocates the appropriate amount of storage.

MATLAB is case sensitiveMATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a are not the same variable.

To view a value, a vector or a matrix assigned to any variable, simply enter the variable name followed by a carriage return.

Page 24: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

NumbersNumbers MATLAB uses conventional decimal notation. Scientific notation uses the letter e to specify

a power-of-ten scale factor. Imaginary numbers use either i or j as a

suffix. All numbers are stored internally using the

long format specified by the IEEE floating-point standard.

Examples – 3, -99, 0.0001, 9.6397238, 1.60210e-20, 6.02252e23, 1i, -3.14159j, 3e5i

Page 25: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

OperatorsOperators + Addition - Subtraction * Multiplication / Division \ Left division (described in “Matrices

and Linear Algebra” in the MATLAB documentation)

^ Power ' Complex conjugate or transpose ( ) Specify evaluation order

Page 26: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

FunctionsFunctions MATLAB provides a large number of standard functio

ns, including abs, sqrt, exp, and sin, etc. Taking the square root or logarithm of a negative num

ber is not an error; the appropriate complex result is produced automatically.

MATLAB also provides many more advanced mathematical functions, including Bessel and gamma functions. Most of these functions accept complex arguments.

For a list of the elementary mathematical functions, type ‘help elfun’

For a list of more advanced mathematical or matrix functions, type ‘help specfun’ or ‘help elmat’

Page 27: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Special variables and Special variables and constantsconstants

ans ans - Most recent answer.- Most recent answer. eps eps - Floating point relative accuracy.- Floating point relative accuracy. realmax realmax - Largest positive floating point nu- Largest positive floating point nu

mber.mber. realmin realmin - Smallest positive floating point nu- Smallest positive floating point nu

mber.mber. pipi - 3.1415926535897....- 3.1415926535897.... i, j i, j - Imaginary unit.- Imaginary unit. infinf - Infinity.- Infinity. NaN NaN - Not-a-Number.- Not-a-Number. isnan isnan - True for Not-a-Number.- True for Not-a-Number. isinfisinf - True for infinite elements.- True for infinite elements. isfinite isfinite - True for finite elements.- True for finite elements.

Page 28: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Overwrite and restoreOverwrite and restore Function or variable names are not reserved.Function or variable names are not reserved.

They can be overwritten and restored. The f They can be overwritten and restored. The following example shows overwriting ollowing example shows overwriting epseps an and restore it back.d restore it back.>> format compact>> epsans = 2.2204e-016>> eps=1.e-6;>> epseps = 1.0000e-006>> clear eps>> epsans = 2.2204e-016>>

>> realmaxans = 1.7977e+308>> realminans = 2.2251e-308>> a=3/0;Warning: Divide by zero.>> aa = Inf>> isinf(3/0)Warning: Divide by zero.ans = 1>>

Page 29: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

FORMATFORMAT FORMAT with no inputs sets the output FORMAT with no inputs sets the output

format to the default appropriate for the format to the default appropriate for the class of the variable. For float variables, the class of the variable. For float variables, the default is FORMAT SHORT.default is FORMAT SHORT.

FORMAT does not affect how MATLAB FORMAT does not affect how MATLAB computations are done. Computations on computations are done. Computations on float variables, namely single or double, are float variables, namely single or double, are done in appropriate floating point precision, done in appropriate floating point precision, no matter how those variables are no matter how those variables are displayed. displayed.

FORMAT SHORT and LONG do not affect FORMAT SHORT and LONG do not affect the display of integer variables.the display of integer variables.

Detailed usage of FORMAT may be found via ‘help format’.

Page 30: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

FORMAT may be used to switch between different FORMAT may be used to switch between different output display formats of all float variables as follooutput display formats of all float variables as follows:ws: FORMAT SHORTFORMAT SHORT - Scaled fixed point format with 5 digit - Scaled fixed point format with 5 digit

s.s. FORMAT LONGFORMAT LONG - Scaled fixed point format with 15 digits - Scaled fixed point format with 15 digits

for double and 7 digits for single.for double and 7 digits for single. FORMAT COMPACTFORMAT COMPACT - Suppresses extra line-feeds. - Suppresses extra line-feeds. FORMAT LOOSEFORMAT LOOSE - Puts the extra line-feeds back in. - Puts the extra line-feeds back in.

Example:Example: format short, pi, single(pi)format short, pi, single(pi) format long, pi, single(pi)format long, pi, single(pi)

Page 31: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

>> format compact>> format long, pi, single(pi)ans = 3.14159265358979ans = 3.1415927>> format loose>> format long, pi, single(pi)

ans =

3.14159265358979

ans =

3.1415927

>>

Effect upon using COMPACT or LOOSE.

Page 32: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

INPUTINPUT INPUT - Prompt for user input. INPUT - Prompt for user input. R = INPUT('How many apples')R = INPUT('How many apples') gives the user t gives the user t

he prompt in the text string and then waits for inhe prompt in the text string and then waits for input from the keyboard. The input can be any MAput from the keyboard. The input can be any MATLAB expression, which is evaluated, using the TLAB expression, which is evaluated, using the variables in the current workspace, and the resuvariables in the current workspace, and the result returned in R. If the user presses the return klt returned in R. If the user presses the return key without entering anything, INPUT returns an ey without entering anything, INPUT returns an empty matrix.empty matrix.

R = INPUT('What is your name','s')R = INPUT('What is your name','s') gives the pr gives the prompt in the text string and waits for character stompt in the text string and waits for character string input. The typed input is not evaluated; the ring input. The typed input is not evaluated; the characters are simply returned as a MATLAB stricharacters are simply returned as a MATLAB string.ng.

Page 33: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

2. Graphics2. Graphics

Page 34: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Plotting ToolsMATLAB Plotting Tools There are two basic ways to create graphs in

MATLAB: Use plotting tools to create graphs interactively.

See “Examples — Using MATLAB Plotting Tools” on page 3-20.

Use the command interface to enter commands in the Command Window or create plotting programs. See “Basic Plotting Functions” on page 3-38.

You might find it useful to combine both approaches. For example, you might issue a plotting command to create a graph and then modify the graph using one of the interactive tools.

Page 35: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Plotting ToolsMATLAB Plotting Tools

From MATLAB workspace, enter the fFrom MATLAB workspace, enter the following data and commands (Try this ollowing data and commands (Try this yourself):yourself):

>> clear>> clear

>> x = -1:.1:1;>> x = -1:.1:1;

>> y = x.^3;>> y = x.^3;

>> plottools>> plottools

Be aware of the “dot” used here.This is needed since x is a vectorinstead of a scalar. A dot like thisshould prefix to your operatorwhenever there exists suchambiguity. (Try what may happenif you do not have this dot?)

Clear all MATLAB variables (optional)

Page 36: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Variables in the workspace. Since we did “clear” ahead, there are only two variables here.

Figure plotting area.

Page 37: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Select x and y (use shift-click for selecting more thaSelect x and y (use shift-click for selecting more than one target), then right-click to select “plot(x,y)” n one target), then right-click to select “plot(x,y)” from the context menu.from the context menu.

Use the Property EditorProperty Editor to customizethe graph. Experiment by yourself.

Page 38: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Command-line PlottingCommand-line Plotting

Try the following commandsTry the following commands>> x=0:pi/100:2*pi;>> x=0:pi/100:2*pi;

>> y=sin(x);>> y=sin(x);

>> plot(x,y)>> plot(x,y)

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

>> ylabel(‘Sine of x’)>> ylabel(‘Sine of x’)

>> title(‘Plot of the Sine Function’,’FontSize’,12)>> title(‘Plot of the Sine Function’,’FontSize’,12)

>> y2=sin(x-.25);y3=sin(x-.5);>> y2=sin(x-.25);y3=sin(x-.5);

>> plot(x,y,x,y2,x,y3)>> plot(x,y,x,y2,x,y3)

>> plot(x,y,’ks’)>> plot(x,y,’ks’)

>> plot(x,y2,’r:+’)>> plot(x,y2,’r:+’)

Observe how this backward slash contributesto the outfitting of this ‘pi’. This is called aTEX syntax in publishing business.

1

2

3

4

Stop at the end of each block to see how the graph changes.

Page 39: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Line styles and colorsLine styles and colors It is possible to specify color, line styles, and ma

rkers (such as plus signs or circles) when you plot your data using the plot command “plot(x,y,'color_style_marker'), where color_style_marker is a string containing from one to four characters (enclosed in single quotation marks) constructed from a color, a line style, and a marker type: Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. Thes

e correspond to cyan, magenta, yellow, red, green, blue, white, and black.

Line style strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot. Omit the line style for no line.

The marker types are '+', 'o', '*', and 'x', and the filled marker types are 's' for square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram, and none for no marker.

Page 40: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics
Page 41: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

3. Using M-files3. Using M-files

Page 42: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

The M-filesThe M-files MATLAB is a powerful programming language as

well as an interactive computational environment. Files that contain code in the MATLAB language

are called M-files. You create M-files using a text editor, then use

them as you would any other MATLAB function or command.

There are two kinds of M-files: Scripts, which do not accept input arguments or return

output arguments. They operate on data in the workspace.

Functions, which can accept input arguments and return output arguments. Internal variables are local to the function.

Page 43: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Example 1Example 1

Use the MATLAB Editor or another text editor to create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m.

For example, create CSIE.m containing the above content, and type ‘CSIE’ in MATLAB.

Name=input(‘Hello. Tell me your name, please: ‘,’s’);Age=input(‘Now tell me how old you are: ‘);if (Age < 13) disp(Name) disp(‘Sorry. You are too young for this movie.’)else disp(Name) disp(‘Welcome to the show. Enjoy.’)end

Page 44: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

Using 3rd-party M-filesUsing 3rd-party M-files

In many cases we may use M-files In many cases we may use M-files developed by someone else. developed by someone else.

These M-files are stored in a given These M-files are stored in a given directory you chose. directory you chose.

Change the working directory to the Change the working directory to the folder containing these M-files. Now folder containing these M-files. Now you will see them and may readily you will see them and may readily use them.use them.

Page 45: Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics

MATLAB Homework #1MATLAB Homework #1 Build an M-file which plots the solution Build an M-file which plots the solution yy((xx) )

as shown in Figure 31 of your text book, usinas shown in Figure 31 of your text book, using g xx incremented at incremented at /100, at the interval [0, 3/100, at the interval [0, 30]. You 0]. You mustmust also plot the two dashed curves. also plot the two dashed curves.

Show your source code and graph.Show your source code and graph.