MATLAB - Tutorialspoint

Transcription

MATLAB

MATLABAbout the TutorialMATLAB is a programming language developed by MathWorks. It started out as amatrix programming language where linear algebra programming was simple. Itcan be run both under interactive sessions and as a batch job.This tutorial gives you aggressively a gentle introduction of MATLAB programminglanguage. It is designed to give students fluency in MATLAB programminglanguage. Problem-based MATLAB examples have been given in simple and easyway to make your learning fast and effective.AudienceThis tutorial has been prepared for the beginners to help them understand basicto advanced functionality of MATLAB. After completing this tutorial you will findyourself at a moderate level of expertise in using MATLAB from where you cantake yourself to next levels.PrerequisitesWe assume you have a little knowledge of any computer programming andunderstand concepts like variables, constants, expressions, statements, etc. If youhave done programming in any other high-level language like C, C or Java,then it will be very much beneficial and learning MATLAB will be like a fun for you.Copyright & Disclaimer Notice Copyright 2014 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comi

MATLABTable of ContentsAbout the Tutorial ······· iAudience ····················· iPrerequisites ··············· iCopyright & Disclaimer Notice ············· iTable of Contents ······· ···· 1MATLAB's Power of Computational Mathematics ········ 1Features of MATLAB ··· 1Uses of MATLAB ········· ······················· 3Local Environment �······················· 3Understanding the MATLAB Environment ···················· 43.BASIC SYNTAX ·················· 7Hands on ··········· 7Use of Semicolon (;) in MATLAB ·········· 8Adding Comments ······ 8Commonly used Operators and Special Characters ······ 9Special Variables and Constants ········ 10Naming Variables ····· 11Saving Your Work ····· 114.VARIABLES ····················· 12Multiple �···· 13I have forgotten the ··············· 13Long Assignments ···· 14ii

MATLABThe format Command ······················· 15Creating Vectors ······· 17Creating Matrices ····· 185.COMMANDS ·················· 20Commands for Managing a Session ··· 20Commands for Working with the System ··················· 20Input and Output Commands ············ 22Vector, Matrix, and Array Commands ························ 23Plotting Commands ·· 256.M-FILES ························· 27The M Files ··············· 27Creating and Running Script File ········ 277.DATA TYPES ··················· 30Data Types Available in MATLAB ······· 30Data Type Conversion ······················· 32Determination of Data Types ············ 348.OPERATORS ··················· 39Arithmetic Operators ························ 39Functions for Arithmetic Operations · 42Relational Operators ························· 46Logical Operators ····· 49Functions for Logical Operations ······· 50Bitwise Operations ··· 55Set Operations ········· 579.DECISION ············ 60iii

MATLABif. end Statement ··· 61if.else.end Statement ···················· 63if.elseif.elseif.else.end · 64The Nested if Statements ·················· 66The switch Statement ······················· 67The Nested Switch Statements ·········· 6910. LOOP TYPES ··················· 71The while Loop ········· 72The for Loop ············· 73The Nested Loops ····· 76Loop Control ························ 78The break Statement ························· 79The continue Statement ···················· 8011. VECTORS ······················· 83Row Vectors ············· 83Column Vectors ········ 83Referencing the Elements of a Vector ························ 84Vector Operations ···· 85Addition and Subtraction of Vectors · 85Scalar Multiplication of Vectors ········ 86Transpose of a Vector ······················· 86Appending Vectors ··· 87Magnitude of a Vector ······················ 89Vector Dot Product ·· 90Vectors with Uniformly Spaced Elements ··················· 90iv

MATLAB12. ···· 92Referencing the Elements of a Matrix ························ 92Deleting a Row or a Column in a Matrix ····················· 94Matrix Operations ···· 96Addition and Subtraction of Matrices ························ 96Division (Left, Right) of Matrix ·········· 97Scalar Operations of Matrices ··········· 98Transpose of a Matrix ······················· 99Concatenating Matrices ···················· 99Matrix Multiplication ······················ 101Determinant of a Matrix ················· 102Inverse of a Matrix · 10213. ARRAYS ························ 104Special Arrays in MATLAB ··············· 104A Magic Square ······ 106Multidimensional Arrays ················· 106Array Functions ······ 109Sorting Arrays ········ 112Cell Array ··············· 113Accessing Data in Cell Arrays ··········· 11414. COLON ··········· 11615. NUMBERS ···················· 119Conversion to Various Numeric Data Types ·············· 119Smallest and Largest Integers ·········· 121Smallest and Largest Floating Point Numbers ·········· 123v

MATLAB16. �· 125Rectangular Character Array ··········· 126Combining Strings into a Cell Array · 128String Functions in MATLAB ············ 12917. FUNCTIONS ················· 134Anonymous Functions ····················· 135Nested Functions ··· 138Private Functions ··· 139Global Variables ····· 14018. DATA ················· 142Low-Level File �···· 146Import Text Data Files with Low-Level I/O ··············· 14719. DATA OUTPUT ············· 152Writing to Diary Files ······················· 154Exporting Data to Text Data Files with Low-Level I/O ························ 15420. PLOTTING ···················· 156Adding Title, Labels, Grid Lines, and Scaling on the �··················· 158Drawing Multiple Functions on the Same Graph ······ 159Setting Colors on Graph ·················· 160Setting Axis Scales ·· 161Generating Sub-Plots ······················ 16221. GRAPHICS ···················· 164Drawing Bar Charts ························· 164Drawing Contours ·· 165Three-Dimensional Plots ················· 167vi

MATLAB22. ALGEBRA ····················· 169Solving Basic Algebraic Equations in MATLAB ·········· 169Solving Quadratic Equations in MATLAB ·················· 171Expanding and Collecting Equations in MATLAB ······· 176Expanding and Collecting Equations in Octave ········· 177Factorization and Simplification of Algebraic Expressions ················· 17923. ························ 181Calculating Limits ··· 181Verification of Basic Properties of Limits using Octave ······················ 184Left and Right Sided Limits ·············· 18524. DIFFERENTIAL ·············· 188Verification of Elementary Rules of Differentiation ·· 189Derivatives of Exponential, Logarithmic, and Trigonometric Functions ······················ 193Computing Higher Order �···· 198Finding the Maxima and Minima of a Curve ············· 200Solving Differential Equations ········· 20425. INTEGRATION ·············· 206Finding Indefinite Integral Using MATLAB ················ 206Finding Definite Integral Using MATLAB ··················· 21026. POLYNOMIALS ············· 216Evaluating Polynomials ··················· 216Polynomial Curve Fitting ················· 21727. TRANSFORMS ·············· 219The Laplace Transform ···················· 219The Inverse Laplace Transform ········ 220vii

MATLABThe Fourier Transforms ··················· 222Inverse Fourier Transforms ············· 22428. GNU OCTAVE TUTORIAL ······················· 225MATLAB vs Octave · 22529. SIMULINK ···················· 229Using ············ 230viii

1. OVERVIEWMATLABMATLAB (matrix laboratory) is a fourth-generation high-level programming languageand interactive environment for numerical computation, visualization andprogramming.MATLAB is developed by MathWorks.It allows matrix manipulations; plotting of functions and data; implementation ofalgorithms; creation of user interfaces; interfacing with programs written in otherlanguages, including C, C , Java, and FORTRAN; analyze data; develop algorithms;and create models and applications.It has numerous built-in commands and math functions that help you in mathematicalcalculations, generating plots, and performing numerical methods.MATLAB's Power of Computational MathematicsMATLAB is used in every facet of computational mathematics. Following are somecommonly used mathematical calculations where it is used most commonly: Dealing with Matrices and Arrays 2-D and 3-D Plotting and graphics Linear Algebra Algebraic Equations Non-linear Functions Statistics Data Analysis Calculus and Differential Equations Numerical Calculations Integration Transforms Curve Fitting Various other special functions9

MATLABFeatures of MATLABFollowing are the basic features of MATLAB: It is a high-level language for numerical computation, visualization andapplication development. It also provides an interactive environment for iterative exploration, designand problem solving. It provides vast library of mathematical functions for linear algebra, statistics,Fourier analysis, filtering, optimization, numerical integration and solvingordinary differential equations. It provides built-in graphics for visualizing data and tools for creating customplots. MATLAB's programming interface gives development tools for improving codequality, maintainability, and maximizing performance. It provides tools for building applications with custom graphical interfaces. It provides functions for integrating MATLAB based algorithms with externalapplications and languages such as C, Java, .NET and Microsoft Excel.Uses of MATLABMATLAB is widely used as a computational tool in science and engineeringencompassing the fields of physics, chemistry, math and all engineering streams. Itis used in a range of applications including: signal processing and Communications image and video Processing control systems test and measurement computational finance computational biology10

2. ENVIRONMENTMATLABLocal Environment SetupSetting up MATLAB environment is a matter of few clicks. The installer can bedownloaded from http://in.mathworks.com/downloads/web downloads:MathWorks provides the licensed product, a trial version and a student version aswell. You need to log into the site and wait a little for their approval.After downloading the installer the software can be installed through few clicks.11

MATLABUnderstanding the MATLAB EnvironmentMATLAB development IDE can be launched from the icon created on the desktop. Themain working window in MATLAB is called the desktop. When MATLAB is started, thedesktop appears in its default layout:The desktop has the following panels:12

MATLABCurrent Folder - This panel allows you to access the project folders and files.Command Window - This is the main area where commands can be entered at thecommand line. It is indicated by the command prompt ( ).Workspace - The workspace shows all the variables created and/or imported fromfiles.13

MATLABCommand History - This panel shows or rerun commands that are entered at thecommand line.Set up GNU OctaveIf you are willing to use Octave on your machine (Linux, BSD, OS X or Windows),then kindly download latest version from ou can check the given installation instructions for your machine14

3. BASIC SYNTAXMATLABMATLAB environment behaves like a super-complex calculator. You can entercommands at the command prompt.MATLAB is an interpreted environment. In other words, you give a command andMATLAB executes it right away.Hands on PracticeType a valid expression, for example,5 5And press ENTERWhen you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:ans 10Let us take up few more examples:3 2% 3 raised to the power of 2When you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:ans 9Another example,sin(pi/2)% sine of angle 90oWhen you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:15

MATLABans 1Another example,7/0% Divide by zeroWhen you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:ans Infwarning: divisionby zeroAnother example,732 * 20.3When you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:ans 1.4860e 04MATLAB provides some special expressions for some mathematical symbols, like pifor π, Inf for , i (and j) for -1 etc. Nan stands for 'not a number'.Use of Semicolon (;) in MATLABSemicolon (;) indicates end of statement. However, if you want to suppress and hidethe MATLAB output for an expression, add a semicolon after the expression.For example,x 3;y x 5When you click the Execute button, or type Ctrl E, MATLAB executes it immediatelyand the result returned is:16

MATLABy 8Adding CommentsThe percent symbol (%) is used for indicating a comment line. For example,x 9% assign the value 9 to xYou can also write a block of comments using the block comment operators % { and% }.The MATLAB editor includes tools and context menu items to help you add, remove,or change the format of comments.Commonly used Operators and Special CharactersMATLAB supports the following commonly used operators and special characters:OperatorPurpose Plus; addition operator.-Minus; subtraction operator.*Scalar and matrix

MATLAB i About the Tutorial MATLAB is a programming language developed by MathWorks. It started out as a matrix programming language wher