首页 Introduction to MATLAB - Sikander M. Mirza

Introduction to MATLAB - Sikander M. Mirza

举报
开通vip

Introduction to MATLAB - Sikander M. Mirza . . . . . .. . . . . . . . . . . . . . Beginner’s Resource Introduction to Matlab® By Dr. Sikander M. Mirza Department of Physics and Applied Mathematics Pakistan Institute of Engineering and Applied Sciences ...

Introduction to MATLAB - Sikander M. Mirza
. . . . . .. . . . . . . . . . . . . . Beginner’s Resource Introduction to Matlab® By Dr. Sikander M. Mirza Department of Physics and Applied Mathematics Pakistan Institute of Engineering and Applied Sciences Nilore, Islamabad 45650, Pakistan . . . . . . Introduction to Matlab 2 TTaabbllee ooff CCoonntteennttss GENERAL FEATURES.............................................................................................................................. 4 STARTUP .................................................................................................................................................... 4 SIMPLE CALCULATIONS.............................................................................................................................. 5 NUMBERS AND STORAGE............................................................................................................................ 6 VARIABLE NAMES ...................................................................................................................................... 6 CASE SENSITIVITY...................................................................................................................................... 7 FUNCTIONS ................................................................................................................................................ 7 TRIGONOMETRIC FUNCTIONS ..................................................................................................................... 7 SOME ELEMENTARY FUNCTIONS................................................................................................................ 7 VECTORS..................................................................................................................................................... 9 THE ROW VECTORS.................................................................................................................................... 9 THE COLON NOTATION .............................................................................................................................. 9 SECTIONS OF A VECTOR ........................................................................................................................... 10 COLUMN VECTORS................................................................................................................................... 11 TRANSPOSE .............................................................................................................................................. 11 DIARY AND SESSION................................................................................................................................. 12 ELEMENTARY PLOTS AND GRAPHS........................................................................................................... 13 MULTIPLOTS............................................................................................................................................. 15 SUBPLOTS................................................................................................................................................. 16 AXES CONTROL........................................................................................................................................ 17 SCRIPTS .................................................................................................................................................... 17 WORKING WITH VECTORS AND MATRICES............................................................................................... 20 HADAMARD PRODUCT .............................................................................................................................. 22 TABULATION OF FUNCTIONS .................................................................................................................... 22 WORKING WITH MATRICES............................................................................................................... 24 DEFINING MATRICES ................................................................................................................................ 24 SIZE OF MATRICES ................................................................................................................................... 25 THE IDENTITY MATRIX ............................................................................................................................ 26 TRANSPOSE .............................................................................................................................................. 26 DIAGONAL MATRIX.................................................................................................................................. 27 SPY FUNCTION ......................................................................................................................................... 27 SECTIONS OF MATRICES ........................................................................................................................... 28 PRODUCT OF MATRICES ........................................................................................................................... 29 MATLAB PROGRAMMING ................................................................................................................... 29 FOR-LOOPS............................................................................................................................................... 29 LOGICAL EXPRESSIONS ............................................................................................................................ 31 WHILE LOOP ............................................................................................................................................. 32 CONDITIONAL PROGRAMMING ................................................................................................................. 33 FUNCTION M-SCRIPTS............................................................................................................................... 34 RETURN STATEMENT................................................................................................................................ 36 RECURSIVE PROGRAMMING ..................................................................................................................... 36 Introduction to Matlab 3 FUNCTION VISUALIZATION ............................................................................................................... 37 SEMILOG PLOT ......................................................................................................................................... 37 POLAR PLOT ............................................................................................................................................. 38 MESH PLOT .............................................................................................................................................. 39 ELAPSED TIME.......................................................................................................................................... 42 . . . . . . Introduction to Matlab 4 GGeenneerraall FFeeaattuurreess Matlab is an interactive working environment in which the user can carry out quite complex computational tasks with few commands. It was originally developed in 1970s by Cleve Muller. The initial programming was in Fortran and over period of time, it has constantly evolved. The latest version is in C. As far as numerical programming is concerned, it removes programming of many routine tasks and allows one to concentrate on the task encouraging experimentation. The results of calculations can be view both numerically as well as in the form of 2D as well as 3D graphs easily and quickly. It incorporates state-of-the-art numerical solution tools, so one can be confident about the results. Also, quite complex computations can be performed with just a few commands. This is because of the fact that the details of programming are stored in separate script files called the ‘m’- files and they can be invoked directly with their names. An m-file can invoke another m-file when required. In this way, a series of m-files running behind the scene allow execution of the required task easily. The user can write his/her own m-files. All such scripts are text readable files which can be read, modified and printed easily. This open-architecture of Matlab® allows programmers to write their own area specific set of m-files. Some such sets written by various experts world-wide have already been incorporated into the Matlab as tool boxes. So, with standard installations, you will find latterly dozens of tool boxes. If you wish, you can down-load even more from the internet. Startup When you click the Matlab icon, the MS Windows opens up the standard Matlab-window for you which has the following form: Introduction to Matlab 5 The white area in the middle is the work area in which the user types-in the commands which are interpreted directly over there and the results are displayed on screen. The ‘>>’ is Matlab prompt indicating that user can type- in command here. A previously entered command can be reached with the help of up-arrow and down-arrow buttons on the keyboard. Simple Calculations Matlab uses standard arithmetic operators + - / * ^ to indicate addition, subtraction, division, multiplication and raised-to-the-power respectively. For example, in order to calculate the answer for 2+34, one would type the following: » 2+3^4 ans = 83 The first line is the user entered command while the second line is default variable used by Matlab for storing the output of the calculations and the third line shows the result of computation. If you wish to multiply this result with 2, proceed as below: » ans*2 ans = 166 As you can see, the result 83 stored in variable ans gets multiplied with 2, and the result of this new computation is again stored in variable ‘ans.’ In this case, its previous value gets over-written by the new variable value. If you wish, you can define your own variables. For example: » pay=2400 pay = 2400 In this case, you define the variable ‘pay’ and assign the variable a value 2400. Matlab echoes the assignment in the second and third line. This confirms the user that a value of 2400 has been assigned to the variable ‘pay’ which is quite useful at times. If you wish to remove this echo in Matlab, use a semicolon at the end of each command. For example: » c=3*10^8; » The variable ‘c’ has been assigned a value 3x108 and since there is a semicolon at the end of the command, therefore, no echo is seen in this case. The arithmetic operators have the following precedence-levels: 1. Brackets first. In case they are nested, then the sequence is from inner- most to the outermost. . . . . . . Introduction to Matlab 6 2. Raised to power next. 3. Multiplication and division next. If there are such competing operators, then the sequence is from left to right. 4. Addition and subtraction next. In this case also, if there are competing such operators, then the sequence is from left to right Numbers and Storage Matlab performs all calculations in double precision and can work with the following data types: Numbers Details Integer Numbers without any fractional part and decimal point. For example, 786 Real Numbers with fractional part e.g., 3.14159 Complex Numbers having real and imaginary parts e.g., 3+4i. Matlab treats ‘i’ as well as ‘j’ to represent 1− Inf Infinity e.g., the result of divided with zero. NaN Not a number e.g., 0/0 For display of the results, Matlab uses Format command to control the output: Category Details format short 4 decimal places (3.1415) format short e 4 decimal places with exponent (3.1415e+00) format long e normal with exponent (3.1415926535897e+00) format bank 2 decimal places (3.14) By using ‘format’ without any suffix means that from now onwards, the default format should be used. Also, ‘format compact’ suppresses any blank lines in the output. Variable Names Matlab allows users to define variable with names containing letters and digits provided that they start with a letter. Hyphen, % sign and other such characters are not allowed in variable names. Also, reserved names should not be used as variable names. For example, pi, i, j, and e are reserved. Similarly, the names of functions and Matlab commands should also be avoided. Introduction to Matlab 7 Case Sensitivity Matlab command structure is quite similar to the C-language. The variables are case sensitive. So, ALPHA and alpha are treated as separate variables. The case sensitivity is also applicable to Matlab commands. As a general rule, the lower-case variable names as well as commands are typically used. FFuunnccttiioonnss Matlab has a potpourri of functions. Some of these are standard functions including trigonometric functions etc., and others are user-defined functions and third party functions. All of these enable user to carry out complex computational tasks easily. Trigonometric Functions These include sin, cos and tan functions. Their arguments should be in radians. In case data is in degrees, one should convert it to radians by multiplying it with pi/180. For example, let us calculate the value of ( ) ( )oo 27cos27sin 22 + : » (sin(27*pi/180))^2+(cos(27*pi/180))^2 ans = 1 The result of these computations is no surprise. Note that in each case, the argument of the trigonometric function was converted to radians by multiplying it suitably. The inverse functions are invoked by asin, acos and atan. For example, ( )1tan 1− is computed as: » atan(1) ans = 0.7854 Of course, 7854.04/ =π . Some Elementary Functions Typically used common functions include sqrt, exp, log and log10. Note that log function gives the natural logarithm. So, » x=2; sqrt(x), exp(-x), log(x), log10(x) ans = 1.4142 ans = . . . . . . Introduction to Matlab 8 0.1353 ans = 0.6931 ans = 0.3010 Here, all four functions have been tested using the same command. As you can see, the semicolon suppresses the echo while the comma separates various computations. Summary of some functions is given below: Function Stands for abs Absolute value sqrt Square root function sign Signum function conj Conjugate of a complex number imag Imaginary part of a complex number real Real part of a complex number angle Phase angle of a complex number cos Cosine function sin Sine function tan Tangent function exp Exponential function log Natural logarithm log10 Logarithm base 10 cosh Hyperbolic cosine function sinh Hyperbolic sine function tanh Hyperbolic tangent function acos Inverse cosine acosh Inverse hyperbolic cosine asin Inverse sine asinh Inverse hyperbolic sine atan Inverse tan atan2 Two argument form of inverse tan atanh Inverse hyperbolic tan round Round to nearest integer floor Round towards minus infinity fix Round towards zero ceil Round towards plus infinity rem Remainder after division Introduction to Matlab 9 VVeeccttoorrss In Matlab, there are two types of vectors: the row vectors and the column vectors. The Row Vectors The row vectors are entities enclosed in pair of square-brackets with numbers separated either by spaces or by commas. For example, one may enter two vectors U and V as: » U=[1 2 3]; V=[4,5,6]; U+V ans = 5 7 9 The two row vectors were first defined and then their sum U+V was computed. The results are given as a row vector stored as ans. The usual operations with vectors can easily be carried out: » 3*U+5*V ans = 23 31 39 The above example computed the linear combination of U and V. One can combine vectors to form another vector: » W=[U, 3*V] W = 1 2 3 12 15 18 The vector U and V both of length 3, have been combined to form a six component vector W. The components of a vector can be sorted with the help of sort function: » sort([8 4 12 3]) ans = 3 4 8 12 The vector [8 4 12 3] has been sorted. The Colon Notation In order to form a vector as a sequence of numbers, one may use the colon notation. According to which, a:b:c yields a sequence of numbers starting with ‘a’, and possibly ending with ‘c’ in steps of ‘b’. For example 1:0.5:2 yields he following column vector: » 1:0.5:2 ans = 1.0000 1.5000 2.0000 . . . . . . Introduction to Matlab 10 Note that in some cases, the upper limit may not be attainable thing. For example, in case of 1:0.3:2, the upper limit is not reached and the resulting vector in this case is: » 1:0.3:2 ans = 1.0000 1.3000 1.6000 1.9000 If only two of the ‘range’ specifications are given then a unit step size is automatically assumed. For example 1:4 means: » 1:4 ans = 1 2 3 4 In case, the range is not valid, an error message is issued: » 1:-1:5 ans = Empty matrix: 1-by-0 Here, the range of numbers given for the generation of row vector was from 1 to 5 in steps of -1. Clearly, one can not reach 5 from 1 using -1 step size. Therefore, the Matlab indicates that this is an empty matrix. Sections of a Vector Let us define a vector using the range notation: » W=[1:3, 7:9] W = 1 2 3 7 8 9 Now, we would like to extract the middle two elements of this vector. This can be done with the range notation again. As you can see, the middle two elements are 3:4 range. Therefore, the required part of vector can be obtained as: » W(3:4) ans = 7 This really is the required part. There are many interesting things that can now be done using the range notation. For example, range 6:-1:1 is the descending range and when used with part-extraction of vector, it gives: » W(6:-1:1) ans = 9 8 7 3 2 1 which is the vector W with all entries now in reverse order. So, a vector can be flipped easily. The ‘size’ function yields the length of a vector. For a given vector V, V(size(V):-1:1) will flip it. Note that flipping of sections of a vector is also possible. Introduction to Matlab 11 Column Vectors The column vectors in Matlab are formed by using a set of numbers in a pair of square brackets and separating them with semi-colon. Therefore, one can define two column vectors A and B and add them as below: » A=[1;2;3]; B=[4;5;6]; A+B ans = 5 7 9 The two column vectors were defined first and then their sum was obtained. In similar way, all other standard operations with the column vectors can be carried out. Transpose Of course, the convenient way of creating a row vector does not have any similar method for the column vector. But, one can do it by first creating a row vector using the range notation and then transposing the resulting row vector into a column vector. The transpose is obtained with a ` as shown below: » A=[1:4]; B=A' B = 1 2 3 4 Here, first a row vector [1 2 3 4] is formed which is called A. This vector is then transposed to form the B—a column vector. Note: If C is a complex vector, then C’ will give its complex conjugate transpose vector. » C=[1+i, 1-i]; D=C' D = 1.0000 - 1.0000i 1.0000 + 1.0000i The vector C was a complex vector and its complex conjugate is [1-i 1+i] vector. Vector D is clearly its complex conjugate transpose vector. Some times, one does not want the
本文档为【Introduction to MATLAB - Sikander M. Mirza】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_228492
暂无简介~
格式:pdf
大小:532KB
软件:PDF阅读器
页数:0
分类:工学
上传时间:2012-12-08
浏览量:12