Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Introduction to MATLAB Lecture 2b 9/28/2007 Presented to the course IT2015 – Engineering Mathematics."— Presentation transcript:

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

2 MATLAB is a widely used software for working with matrices. MATLAB is a widely used software for working with matrices. Many schools are now using this software, and numerous workshops have been given on its integration to many courses, including linear algebra. Many schools are now using this software, and numerous workshops have been given on its integration to many courses, including linear algebra. In this course we ’ d like to give you a very basic knowledge of using MATLAB in dealing with various topics associated with differential equations. In this course we ’ d like to give you a very basic knowledge of using MATLAB in dealing with various topics associated with differential equations.

3 What is MATLAB? Product of “ The MathWorks, Inc. ” located near Boston, MA, U.S.A. since 1984. Product of “ The MathWorks, Inc. ” located near Boston, MA, U.S.A. since 1984. Current version installed at CSIE lab is MATLAB 7.0.1 (Release 14SP1). Current version installed at CSIE lab is MATLAB 7.0.1 (Release 14SP1). MATLAB = Matrix Laboratory. MATLAB = Matrix Laboratory. MATLAB products are generally divided into “ MATLAB ” (cores) and “ MATLAB Toolbox ”. MATLAB products are generally divided into “ MATLAB ” (cores) and “ MATLAB Toolbox ”.

4 MATLAB product line MATLAB ( 交談式科技計算語言 ) NT 30,000. MATLAB ( 交談式科技計算語言 ) NT 30,000. MATLAB MATLAB COM Builder (COM 物件工具箱 ) MATLAB COM Builder (COM 物件工具箱 ) MATLAB COM Builder MATLAB COM Builder MATLAB Compiler ( 編譯器 ) MATLAB Compiler ( 編譯器 ) MATLAB Compiler MATLAB Compiler MATLAB Report Generator (MATLAB 報告產生器 ) MATLAB Report Generator (MATLAB 報告產生器 ) MATLAB Report Generator MATLAB Report Generator MATLAB Web Server ( 網頁結合工具箱 ) MATLAB Web Server ( 網頁結合工具箱 ) MATLAB Web Server MATLAB Web Server MATLAB Runtime Server ( 獨立程式開發工具箱 ) MATLAB Runtime Server ( 獨立程式開發工具箱 ) MATLAB Runtime Server MATLAB Runtime Server MATLAB Excel Builder (Excel 增益集工具箱 ) MATLAB Excel Builder (Excel 增益集工具箱 ) MATLAB Excel Builder MATLAB Excel Builder Excel Link (for PC) (Excel 連結工具箱 ) Excel Link (for PC) (Excel 連結工具箱 ) Excel Link (for PC) Excel Link (for PC)

5 MATLAB Toolbox - 1 Curve Fitting Toolbox ( 曲線契合工具箱 ) Curve Fitting Toolbox ( 曲線契合工具箱 ) Curve Fitting Toolbox Curve Fitting Toolbox Optimization Toolbox ( 最佳化工具箱 ) Optimization Toolbox ( 最佳化工具箱 ) Optimization Toolbox Optimization Toolbox Statistics Toolbox ( 統計工具箱 ) NT 12,000. Statistics Toolbox ( 統計工具箱 ) NT 12,000. Statistics Toolbox Statistics Toolbox Bioinformatics Toolbox ( 生物資訊工具箱 ) NT$ 12,000. Bioinformatics Toolbox ( 生物資訊工具箱 ) NT$ 12,000. Neural Network Toolbox ( 類神經網路工具箱 ) Neural Network Toolbox ( 類神經網路工具箱 ) 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 ( 雲線函數工具箱 ) Spline Toolbox Spline Toolbox

6 MATLAB Toolbox - 2 Data Acquisition Toolbox ( 資料擷取工具箱 ) Data Acquisition Toolbox ( 資料擷取工具箱 ) Data Acquisition Toolbox Data Acquisition Toolbox Instrument Control Toolbox ( 儀器設備控制工具箱 ) Instrument Control Toolbox ( 儀器設備控制工具箱 ) Instrument Control Toolbox Instrument Control Toolbox Image Acquisition Toolbox ( 影像擷取工具箱 ) Image Acquisition Toolbox ( 影像擷取工具箱 ) Image Acquisition Toolbox Image Acquisition Toolbox Database Toolbox ( 資料庫連結工具箱 ) Database Toolbox ( 資料庫連結工具箱 ) Database Toolbox Database Toolbox Financial Toolbox ( 財經工具箱 ) Financial Toolbox ( 財經工具箱 ) Financial Toolbox Financial Toolbox Financial Time Series Toolbox ( 財務時間序列工具箱 ) Financial Time Series Toolbox ( 財務時間序列工具箱 ) Financial Time Series Toolbox Financial Time Series Toolbox GARCH Toolbox ( 異質條件變異數自我迴歸工具箱 ) GARCH Toolbox ( 異質條件變異數自我迴歸工具箱 ) GARCH Toolbox GARCH Toolbox Financial Derivatives Toolbox ( 衍生性金融商品工具箱 ) Financial Derivatives Toolbox ( 衍生性金融商品工具箱 ) Financial Derivatives Toolbox Financial Derivatives Toolbox Datafeed Toolbox ( 財務資料來源工具箱 ) Datafeed Toolbox ( 財務資料來源工具箱 ) Datafeed Toolbox Datafeed Toolbox Fixed-Income Toolbox ( 固定收益商品工具箱 ) Fixed-Income Toolbox ( 固定收益商品工具箱 ) Fixed-Income Toolbox Fixed-Income Toolbox

7 MATLAB Toolbox - 3 Signal Processing Toolbox ( 信號處理工具箱 ) Signal Processing Toolbox ( 信號處理工具箱 ) Signal Processing Toolbox Signal Processing Toolbox Image Processing Toolbox ( 影像處理工具箱 ) Image Processing Toolbox ( 影像處理工具箱 ) Image Processing Toolbox Image Processing Toolbox Communications Suite ( 通訊工具組合 ) 包含 Communications Suite ( 通訊工具組合 ) 包含 Communications Toolbox & Blockset Communications Toolbox & BlocksetCommunications Toolbox BlocksetCommunications Toolbox Blockset System Identification Toolbox ( 系統辨識工具箱 ) System Identification Toolbox ( 系統辨識工具箱 ) System Identification Toolbox System Identification Toolbox Wavelet Toolbox ( 小波工具箱 ) Wavelet Toolbox ( 小波工具箱 ) Wavelet Toolbox Wavelet Toolbox Filter Design Toolbox ( 濾波器設計工具箱 ) Filter Design Toolbox ( 濾波器設計工具箱 ) Filter Design Toolbox Filter Design Toolbox MATLAB Link for Code Composer Studio ™ Development Tools (MATLAB 與 CCS 連結工具箱 ) MATLAB Link for Code Composer Studio ™ Development Tools (MATLAB 與 CCS 連結工具箱 ) MATLAB Link for Code Composer Studio ™ Development Tools MATLAB Link for Code Composer Studio ™ Development Tools

8 MATLAB Toolbox - 4 Control System Toolbox ( 控制系統工具箱 ) Control System Toolbox ( 控制系統工具箱 ) Control System Toolbox Control System Toolbox Fuzzy Logic Toolbox ( 模糊邏輯工具箱 ) Fuzzy Logic Toolbox ( 模糊邏輯工具箱 ) Fuzzy Logic Toolbox Fuzzy Logic Toolbox Robust Control Toolbox ( 強韌控制工具箱 ) Robust Control Toolbox ( 強韌控制工具箱 ) Robust Control Toolbox Robust Control Toolbox Mu-Analysis & Synthesis Toolbox (Mu 分析及合成工具箱 ) Mu-Analysis & Synthesis Toolbox (Mu 分析及合成工具箱 ) Mu-Analysis & Synthesis Toolbox Mu-Analysis & Synthesis Toolbox LMI Control Toolbox ( 線性矩陣不等式控制工具箱 ) LMI Control Toolbox ( 線性矩陣不等式控制工具箱 ) LMI Control Toolbox LMI Control Toolbox Model Predictive Control Toolbox ( 模型預測控制工具箱 ) Model Predictive Control Toolbox ( 模型預測控制工具箱 ) Model Predictive Control Toolbox Model Predictive Control Toolbox Model-Based Calibration Toolbox (Model-based 調校工具箱 ) Model-Based Calibration Toolbox (Model-based 調校工具箱 ) Model-Based Calibration Toolbox Model-Based Calibration Toolbox

9 Running MATLAB MATLAB is installed to every PC in two CSIE computer labs. MATLAB is installed to every PC in two CSIE computer labs. Each time one runs MATLAB, the license server is contacted and assigns a license to the client (if there is any left). We have a total of 50 licenses available. Each time one runs MATLAB, the license server is contacted and assigns a license to the client (if there is any left). We have a total of 50 licenses available.

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

11

12

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

14

15 1. MATLAB Basics

16 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 Column 1, 2, 3 and 4

17 a 11 a 12 a 13 a 14 a 21 a 22 a 23 a 24 a 31 a 32 a 33 a 34 a 41 a 42 a 43 a 44 a ij = the element at i-th row and j-th column.

18 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 13 5 10 11 8 9 6 7 12 4 15 14 1 Matrix Basics Note that MATLAB always echoes the value for the most recent variable processed, if you did not postfix “ ; ” at the end of line.

19 The first statement to try is “ sum(A) ”. MATLAB replies with ans = 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. Try to get the sum of a row vector x = (1, 2, 3). The sum of a row vector is straightforward. Try to get the sum of a row vector x = (1, 2, 3).

20 The Colon Operator The colon, :, is one of the most important MATLAB operators. The colon, :, is one of the most 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 51 and “ 0:pi/4:pi ” is 0 0.7854 1.5708 2.3562 3.1416

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

22 The magic function MATLAB actually has a built-in function that creates magic squares of almost any size. Not surprisingly, this function is named magic: B = magic(4) B = 16 2 3 13 5 11 10 8 9 7 6 12 4 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]) ”

23 Variables 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 sensitive MATLAB 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.

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

25 Operators + Addition - Subtraction * Multiplication / Division \ Left division (described in “ Matrices and Linear Algebra ” in the MATLAB documentation) ^ Power ' Complex conjugate or transpose ( ) Specify evaluation order

26 Functions MATLAB provides a large number of standard functions, including abs, sqrt, exp, and sin, etc. Taking the square root or logarithm of a negative number 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 ’

27 Special variables and constants ans - Most recent answer. ans - Most recent answer. eps - Floating point relative accuracy. eps - Floating point relative accuracy. realmax - Largest positive floating point number. realmax - Largest positive floating point number. realmin - Smallest positive floating point number. realmin - Smallest positive floating point number. pi - 3.1415926535897.... pi - 3.1415926535897.... i, j - Imaginary unit. i, j - Imaginary unit. inf - Infinity. inf - Infinity. NaN - Not-a-Number. NaN - Not-a-Number. isnan - True for Not-a-Number. isnan - True for Not-a-Number. isinf - True for infinite elements. isinf - True for infinite elements. isfinite - True for finite elements. isfinite - True for finite elements.

28 Overwrite and restore Function or variable names are not reserved. They can be overwritten and restored. The following example shows overwriting eps and restore it back. Function or variable names are not reserved. They can be overwritten and restored. The following example shows overwriting eps and restore it back. >> format compact >> eps ans = 2.2204e-016 >> eps=1.e-6; >> eps eps = 1.0000e-006 >> clear eps >> eps ans = 2.2204e-016 >> >> realmax ans = 1.7977e+308 >> realmin ans = 2.2251e-308 >> a=3/0; Warning: Divide by zero. >> a a = Inf >> isinf(3/0) Warning: Divide by zero. ans = 1 >>

29 FORMAT FORMAT with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default is FORMAT SHORT. FORMAT with no inputs sets the output format to the default appropriate for the class of the variable. For float variables, the default is FORMAT SHORT. FORMAT does not affect how MATLAB computations are done. Computations on float variables, namely single or double, are done in appropriate floating point precision, no matter how those variables are displayed. FORMAT does not affect how MATLAB computations are done. Computations on float variables, namely single or double, are done in appropriate floating point precision, no matter how those variables are displayed. FORMAT SHORT and LONG do not affect the display of integer variables. FORMAT SHORT and LONG do not affect the display of integer variables. Detailed usage of FORMAT may be found via ‘ help format ’.

30 FORMAT may be used to switch between different output display formats of all float variables as follows: FORMAT may be used to switch between different output display formats of all float variables as follows: FORMAT SHORT - Scaled fixed point format with 5 digits. FORMAT SHORT - Scaled fixed point format with 5 digits. FORMAT LONG - Scaled fixed point format with 15 digits for double and 7 digits for single. FORMAT LONG - Scaled fixed point format with 15 digits for double and 7 digits for single. FORMAT COMPACT - Suppresses extra line-feeds. FORMAT COMPACT - Suppresses extra line-feeds. FORMAT LOOSE - Puts the extra line-feeds back in. FORMAT LOOSE - 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)

31 >> format compact >> format long, pi, single(pi) ans = 3.14159265358979 ans = 3.1415927 >> format loose >> format long, pi, single(pi) ans = 3.14159265358979 ans = 3.1415927 >> Effect upon using COMPACT or LOOSE.

32 INPUT INPUT - Prompt for user input. INPUT - Prompt for user input. R = INPUT('How many apples') gives the user the prompt in the text string and then waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. R = INPUT('How many apples') gives the user the prompt in the text string and then waits for input from the keyboard. The input can be any MATLAB expression, which is evaluated, using the variables in the current workspace, and the result returned in R. If the user presses the return key without entering anything, INPUT returns an empty matrix. R = INPUT('What is your name','s') gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string. R = INPUT('What is your name','s') gives the prompt in the text string and waits for character string input. The typed input is not evaluated; the characters are simply returned as a MATLAB string.

33 2. Graphics

34 MATLAB 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.

35 MATLAB Plotting Tools From MATLAB workspace, enter the following data and commands (Try this yourself): From MATLAB workspace, enter the following data and commands (Try this yourself): >> clear >> x = -1:.1:1; >> y = x.^3; >> plottools Be aware of the “ dot ” used here. This is needed since x is a vector instead of a scalar. A dot like this should prefix to your operator whenever there exists such ambiguity. (Try what may happen if you do not have this dot?) Clear all MATLAB variables (optional)

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

37 Select x and y (use shift-click for selecting more than one target), then right-click to select “ plot(x,y) ” from the context menu. Property Editor Use the Property Editor to customize the graph. Experiment by yourself.

38 Command-line Plotting Try the following commands Try the following commands >> x=0:pi/100:2*pi; >> y=sin(x); >> plot(x,y) >> xlabel(‘x = 0:2\pi’) >> ylabel(‘Sine of x’) >> title(‘Plot of the Sine Function’,’FontSize’,12) >> y2=sin(x-.25);y3=sin(x-.5); >> plot(x,y,x,y2,x,y3) >> plot(x,y,’ks’) >> plot(x,y2,’r:+’) Observe how this backward slash contributes to the outfitting of this ‘ pi ’. This is called a T E X syntax in publishing business. 1 2 3 4 Stop at the end of each block to see how the graph changes.

39 Line styles and colors It is possible to specify color, line styles, and markers (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'. These 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.

40

41 3. Using M-files

42 The 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.

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

44 Using 3rd-party M-files In many cases we may use M-files developed by someone else. In many cases we may use M-files developed by someone else. These M-files are stored in a given directory you chose. These M-files are stored in a given directory you chose. Change the working directory to the folder containing these M-files. Now you will see them and may readily use them. Change the working directory to the folder containing these M-files. Now you will see them and may readily use them.

45 MATLAB Homework #1 Build an M-file which plots the solution y(x) as shown in Figure 31 of your text book, using x incremented at  /100, at the interval [0, 30]. You must also plot the two dashed curves. Build an M-file which plots the solution y(x) as shown in Figure 31 of your text book, using x incremented at  /100, at the interval [0, 30]. You must also plot the two dashed curves. Show your source code and graph. Show your source code and graph.


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

Similar presentations


Ads by Google