MATLAB For Beginners - ResearchGate

3y ago
29 Views
1 Downloads
1.29 MB
299 Pages
Last View : 20d ago
Last Download : 3m ago
Upload by : Milo Davies
Transcription

MATLAB for BeginnersA Gentle ApproachRevised EditionPeter I. KattanPetra Books

MATLAB for Beginnerswww.PetraBooks.comvi

Peter I. Kattan, PhDCorrespondence about this book may be sentto the author at one of the following two a.net.joSmashwords EditionMATLAB for Beginners: A Gentle Approach,Revised Edition, written by Peter I. Kattan.All rights reserved. No part of this book may becopied or reproduced without written permission ofthe author or publisher. 2010 Peter I. Kattan

In Loving Memory of My Father

MATLAB for BeginnersA Gentle ApproachRevised Edition

PrefaceThis book is written for people who wish to learnMATLAB1 for the first time. The book is really designedfor beginners and students. In addition, the book is suitablefor students and researchers in various disciplines rangingfrom engineers and scientists to biologists andenvironmental scientists. The book is intended to be used asa first course in MATLAB in these areas. Students at boththe undergraduate level and graduate level may benefitfrom this book. The material presented has been simplifiedto such a degree such that the book may also be used forstudents and teachers in high schools – at least forperforming simple arithmetic and algebraic manipulations.One of the objectives of writing this book is to introduceMATLAB and its powerful and simple computationalabilities to students in high schools.The material presented increases gradually in difficultyfrom the first few chapters on simple arithmetic operationsto the last two chapters on solving equations and anintroduction to calculus. In particular, the materialpresented in this book culminates in Chapters 6 and 7 onvectors and matrices, respectively. There is no discussionof strings, character variables or logical operators in thisbook. The emphasis is on computational and symbolicaspects. In addition, the MATLAB Symbolic MathToolbox2 is emphasized in this book. A section is added atthe end of each chapter (except chapters 1 and 9) dealingwith various aspects of algebraic and symbolic1MATLAB is a registered trademark of the MathWorks, Inc.The MATLAB Symbolic Math Toolbox is a registered trademark ofthe MathWorks, Inc.2

MATLAB for Beginnersvicomputations with the Symbolic Math Toolbox. In fact, thefinal chapter on calculus assumes entirely the use of thistoolbox.Chapter 1 provides an overview of MATLAB and maybe skipped upon a first reading of the book. The actualmaterial in sequence starts in Chapter 2 which deals witharithmetic operations. Variables are introduced in Chapter 3followed by mathematical functions in Chapter 4. Theimportant topic of complex numbers is covered in Chapter5. This is followed by Chapters 6 and 7 on vectors andmatrices, respectively, which provide the main core of thebook. In fact, MATLAB stands for MATrix LABoratory –thus a long chapter is devoted to matrices and matrixcomputations. An introduction to programming usingMATLAB is provided in Chapter 8. Plotting twodimensional and three-dimensional graphs is covered insome detail in Chapter 9. Finally, the last two chapters (10and 11) present solving equations and an introduction tocalculus using MATLAB.The material presented in this book has been tested withversion 7 of MATLAB and should work with any prior orlater versions. There are also over 230 exercises at the endsof chapters for students to practice. Detailed solutions to allthe exercises are provided in the second half of the book.The material presented is very easy and simple tounderstand – written in a gentle manner. An extensivereferences list is also provided at the end of the book withreferences to books and numerous web links for moreinformation. This book will definitely get you started inMATLAB. The references provided will guide you to otherresources where you can get more information.I would like to thank my family members for their helpand continued support without which this book would not

MATLAB for Beginnersviihave been possible. In this edition, I am providing twoemail addresses for my readers to contact me pkattan@alumni.lsu.edu and pkattan@tedata.net.jo.August 2009Peter I. Kattan

MATLAB for BeginnersviiiContents1. Introduction 2. Arithmetic Operations 3. Variables 4. Mathematical Functions 5. Complex Numbers 6. Vectors 7. Matrices .8. Programming 9. Graphs 10. Solving Equations .11. Beginning Calculus Solutions to Exercises .References .Installation of MATLAB .

MATLAB for BeginnersixIndex

MATLAB for Beginners101. IntroductionIn this introductory chapter a short MATLAB tutorial isprovided. This tutorial describes the basic MATLAB commandsneeded. More details about these commands will follow insubsequent chapters. Note that there are numerous free MATLABtutorials on the internet – check references [1-28]. Also, you maywant to consult many of the excellent books on the subject – checkreferences [29-47]. This chapter may be skipped on a first readingof the book.In this tutorial it is assumed that you have started MATLAB onyour computer system successfully and that you are now ready totype the commands at the MATLAB prompt (which is denoted bydouble arrows “ ”). For installing MATLAB on your computersystem, check the web links provided at the end of the book.Entering scalars and simple operations is easy as is shown inthe examples below: 2*3 5ans 11The order of the operations will be discussed in subsequentchapters. cos(60*pi/180)ans 0.5000

MATLAB for Beginners11The argument for the cos command and the value of piwill be discussed in subsequent chapters.We assign the value of 4 to the variable x as follows: x 4x 4 3/sqrt(2 x)ans 1.2247To suppress the output in MATLAB use a semicolon to endthe command line as in the following examples. If the semicolon isnot used then the output will be shown by MATLAB: yzxw 30;8;2; y-z;4*y 3*zw 144MATLAB is case-sensitive, i.e. variables with lowercaseletters are different than variables with uppercase letters. Considerthe following examples using the variables x and X: x 1

MATLAB for Beginners12x 1 X 2X 2 xx 1 XX 2Use the help command to obtain help on any particularMATLAB command. The following example demonstrates the useof help to obtain help on the det command which calculatedthe determinant of a matrix: help detDETDeterminant.DET(X) is the determinant of the squarematrix X.Use COND instead of DET to test formatrix singularity.

MATLAB for Beginners13See also cond.Overloaded functions or methods (oneswith the same name in other directories)help sym/det.mReference page in Help browserdoc detThe following examples show how to enter matrices andperform some simple matrix operations: x [1 2 3 ; 4 5 6 ; 7 8 9]x 147258369 y [1 ; 0 ; -4]y 10-4 w x*yw -11-20-29

MATLAB for Beginners14Let us now see how to use MATLAB to solve a system ofsimultaneous algebraic equations. Let us solve the followingsystem of simultaneous algebraic equations: 3 5 1 x1 2 0 4 2 x 1 2 2 1 5 x3 4 (1.1)We will use Gaussian elimination to solve the abovesystem of equations. This is performed in MATLAB by using thebackslash operator “\” as follows: A [3 5 -1 ; 0 4 2 ; -2 1 5]A 30-2541-125 b [2 ; 1 ; -4]b 21-4 x A\bx -1.76921.1154-1.7308

MATLAB for Beginners15It is clear that the solution is x1 -1.7692, x2 1.1154, andx3 -1.7308. Alternatively, one can use the inverse matrix of A toobtain the same solution directly as follows: x inv(A)*bx -1.76921.1154-1.7308It should be noted that using the inverse method usuallytakes longer than using Gaussian elimination especially for largesystems of equations.Consider now the following 4 x 4 matrix D: D [1 2 3 4 ; 2 4 6 8 ; 3 6 9 12 ; -5 -3-1 0]D 123-5246-3369-148120We can extract the sub-matrix in rows 2 to 4 and columns 1to 3 as follows: E D(2:4, 1:3)E

MATLAB for Beginners23-546-31669-1We can extract the third column of D as follows: F D(1:4, 3)F 369-1We can extract the second row of D as follows: G D(2, 1:4)G 2468We can also extract the element in row 3 and column 2 asfollows: H D(3,2)H 6We will now show how to produce a two-dimensional plotusing MATLAB. In order to plot a graph of the functiony f (x) , we use the MATLAB command plot(x,y) after we

MATLAB for Beginners17have adequately defined both vectors x and y. The following is asimple example to plot the function y x 2 3 for a certain range: x [1 2 3 4 5 6 7 8 9 10 11]x Columns 1 through 101982103456719283952Column 1111 y x. 2 3y Columns 1 through 1048467710312Column 11124 plot(x,y)Figure 1.1 shows the plot obtained by MATLAB. It isusually shown in a separate window. In this figure no titles aregiven to the x- and y-axes. These titles may be easily added to thefigure using the xlabel and ylabel commands. More detailsabout these commands will be presented in the chapter on graphs.

MATLAB for Beginners18In the calculation of the values of the vector y, notice thedot “.” before the exponentiation symbol “ ”. This dot is used todenote that the operation following it be performed element byelement. More details about this issue will be discussed insubsequent chapters.Figure 1.1: Using the MATLAB "plot" commandFinally, we will show how to make magic squares withMATLAB. A magic square is a square grid of numbers where thetotal of any row, column, or diagonal is the same. Magic squaresare produced by MATLAB using the command magic. Here is asimple example to produce a 5 x 5 magic square: magic(5)ans 1723245178141516

MATLAB for Beginners410116121819131925202122239It is clear that the total of each row, column or diagonal in theabove matrix is 65.ExercisesSolve all the exercises using MATLAB. All the neededMATLAB commands for these exercises were presented in thischapter.1. Perform the operation 3*4 6. The order of the operationswill be discussed in subsequent chapters.2. Perform the operation cos(5) . The value of 5 is in radians.3. Perform the operation3 6 xfor x 4 .4. Assign the value of 5.2 to the variable y.5. Assign the values of 3 and 4 to the variables x and y,respectively, then calculate the value of z wherez 2x 7 y .6. Obtain help on the inv command.7. Generate the following matrix: A 1 0A 1 205202231 3 2 4 3

MATLAB for Beginners208. Generate the following vector b 1 2 b 3 4 9. Evaluate the vector c where {c} [ A]{b} where A is thematrix given in Exercise 7 above and b is the vector givenin Exercise 8 above.10. Solve the following system of simultaneous algebraicequation using Gaussian elimination. 5 2 x1 3 1 3 x 1 2 11. Solve the system of simultaneous algebraic equations ofExercise 10 above using matrix inversion.12. Generate the following matrix X: 1X 1 40256 3 2 13. Extract the sub-matrix in rows 2 to 3 and columns 1 to 2 ofthe matrix X in Exercise 12 above.14. Extract the second column of the matrix X in Exercise 12above.15. Extract the first row of the matrix X in Exercise 12 above.

MATLAB for Beginners2116. Extract the element in row 1 and column 3 of the matrix Xin Exercise 12 above.17. Generate the row vector x with integer values ranging from1 to 9.18. Plot the graph of the function y x 3 2 for the range ofthe values of x in Exercise 17 above.19. Generate a 4 x 4 magic square. What is the total of eachrow, column, and diagonal in this matrix.

MATLAB for Beginners222. Arithmetic OperationsIn this chapter we learn how to perform the simple arithmeticoperations of addition, subtraction, multiplication, division, andexponentiation. The first four operations of addition, subtraction,multiplication, and division are performed in MATLAB using theusual symbols , -, *, and /. The following are some examples: 5 6ans 11 12-9ans 3 3*4ans 12 4/2ans 2 4/3ans

MATLAB for Beginners231.3333In the next chapter, we will show how to control thenumber of decimal digits that appear in the answer. The operationof exponentiation is performed using the symbol as shown in thefollowing examples: 2 3ans 8 2 -3ans 0.1250 -2 3ans -8 -2 4ans -16 (-2) 4ans

MATLAB for Beginners2416In the above examples, be careful where the minus sign isused. The constants π and ε are obtained in MATLAB asfollows: pians 3.1416 epsans 2.2204e-016In the above examples, the constant π is denoted by the commandpi and represents the ratio of the perimeter of a circle to itsdiameter. The other constant ε is denoted by the command epsand represents the smallest number that MATLAB can handle.In the above examples, only one arithmetic operation wasperformed in each line. Alternatively, we can perform multiplearithmetic operations in each line or command. The following aresome examples: 2 3-7ans -2 3*4 5

MATLAB for Beginners25ans 17 2 5/4ans 3.2500In these cases, the order of operations is very importantbecause the final computed result depends on this order.Precedence of computation is for the exponentiation operation,followed by multiplication and division, then followed by additionand subtraction. For example, in the examples above,multiplication is performed before addition and division isperformed before addition. In case you need to perform additionbefore multiplication or division, the above two examples may becomputed using parentheses as follows: 3*(4 5)ans 27 (2 5)/4ans 1.7500It is clear from the above examples that the operationsinside the parentheses take precedence over any other operations.Several multiple operations may also be performed as follows:

MATLAB for Beginners26 (26 53)-(3 4 5)*2/3ans 21.6667One should be careful when using parentheses. A change ofthe position of the parenthesis in the above example will changethe computed results as follows: (26 53)-(3 4 5*2)/3ans 48.6667ArithmeticOperationsSymbolic Math ToolboxwiththeMATLABSymbolic arithmetic operations may also be performed inMATLAB using the MATLAB Symbolic Math Toolbox. For thenext examples, this toolbox needs to be installed with MATLAB.In order to perform symbolic operations in MATLAB, we need todefine symbolic numbers3 using the sym command. For example,½ is defined as a symbolic number as follows: sym(1/2)ans 1/23Actually these are symbolic objects in MATLAB but objects are beyond thescope of this book.

MATLAB for Beginners27In the above example, the number ½ is stored in MATLABwithout any approximation using decimal digits like 0.5. Onceused with the sym command, the computations will be performedalgebraically or symbolically. For example, the following additionof two fractions is performed numerically as follows without thesym command: 1/2 3/5ans 1.1000Adding parenthesescomputation in this case:willnot affectthenumerical (1/2) (3/5)ans 1.1000However, using the sym command of the MATLABSymbolic Math Toolbox will result in the computation performedsymbolically without the use of decimal digits; sym((1/2) (3/5))ans 11/10Notice in the above example how the final answer was castin the form of a fraction without decimal digits and withoutcalculating a numerical value. In the addition of the two fractionsabove, MATLAB finds their common denominator and adds them

MATLAB for Beginners28by the usual procedure for rational numbers. Notice also in theabove four example outputs that symbolic answers are not indentedbut numerical answers are indented. In the next chapter, we willstudy variables and their use in MATLAB.ExercisesSolve all the exercises using MATLAB. All the neededMATLAB commands for these exercises were presented in thischapter. Note that Exercises 19 and 21 require the use of theMATLAB Symbolic Math Toolbox.1. Perform the addition operation 7 9.2. Perform the subtraction operation 16-10.3. Perform the multiplication operation 2*9.4. Perform the division operation 12/3.5. Perform the division operation 12/5.6. Perform the exponentiation operation 3 5.7. Perform the exponentiation operation 3*(-5).8. Perform the exponentiation operation (-3) 5.9. Perform the exponentiation operation -3 5.10. Compute the value of2π.3

MATLAB for Beginners2911. Obtain the value of the smallest number that can be handledby MATLAB.12. Perform the multiple operations 5 7-15.13. Perform the multiple operations (6*7) 4.14. Perform the multiple operations 6*(7 4).15. Perform the multiple operations 4.5 (15/2).16. Perform the multiple operations (4.5 15)/2.17. Perform the multiple operations (15 – 4 12)/5 – 2*(7 4)/100.18. Perform the multiple operations (15 – 4) 12/5 –(2*7) 4/100.19. Define the number 2/3 as a symbolic number.20. Perform the fraction addition (2/3) (3/4) numerically.21. Perform the fraction addition (2/3) (3/4) symbolically.

MATLAB for Beginners303. VariablesIn this chapter we introduce variables and how to deal withthem in MATLAB. If you do not use a variable, then MATLABautomatically stores the calculated result in the variable ans. Thefollowing is an example: 3 2ans 5In the above example, the number 5 is stored automaticallyin the variable ans. This variable is short for “answer”. If youwish to store the number 5 in another variable, then you need tospecify it as follow: x 3 2x 5In the above example, we used the variable x to store theresult which is 5. You may define the variables x, y, z as followswithout performing any operations: x 1x 1 y -3

MATLAB for Beginners31y -3 z 3.52z 3.5200Note that MATLAB is case-sensitive with respect tovariables. For example, the variables x and X are different. Thefollowing example illustrates this issue: x 5x 5 X 3X 3 xx 5 XX

MATLAB for Beginners323We may perform arithmetic operations on variables asshown in the following examples: x 4x 4 y 2.5y 2.5000 z x yz 6.5000 w 2*x-3*z yw -9Up till now, we have used single letters to denote variables.Any string of characters may be used to denote variables also. Forexample, we next use the variables result andthe answer is as follows: a 3

MATLAB for Beginners33a 3 b -2b -2 result a*bresult -6 the answer is 2*a/bthe answer is -3Since MATLAB is case-sensitive, then the variableswidth, WIDTH, and Width are all different and store differentresults. You may add comments to your MATLAB commands andstatements by using the symbol %. Comments are not executed andare ignored by MATLAB but are included for the benefit of thereader. For example, here is a comment: % This is a commentComments are displayed in green color on the MATLABscreen. You may also add a comment on the same line as acommand. The following is an example:

MATLAB for Beginners x 634% the value of x is defined herex 6The following are the MATLAB rules for naming variables:1.2.3.4.5.6.MATLAB is case-sensitive with respect to variables.All variables must start with a letter.You may have up to 31 characters in a variable.Punctuation signs are not allowed in a variable.The underscore sign “ ” is allowed in a variable.Both letters and digits are allowed in a variable.For example, we may define variables x1, x2, and x3 asfollows: x1 1x1 1 x2 -2.7x2 -2.7000 x3 2*x1/x2x3 -0.7407

MATLAB for Beginners35All variable used must be defined. For example, we get anerror if we try to use a variable that is not defined. For example,the variable h is not defined as follows: 3*h/2? Undefined function or variable 'h'.The error is displayed in red color on the MATLAB screen.To find all the variables used in a MATLAB session, use the whocommand as follows: whoYour variables are:Xaansbresultthe answer iswxx1x2x3yzThe who

MATLAB for Beginners A Gentle Approach Revised Edition. Preface This book is written for people who wish to learn MATLAB1 for the first time. The book is really designed for beginners and students .

Related Documents:

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for algebra, plotting, calculus, and solving differential .

19 MATLAB Excel Add-in Hadoop MATLAB Compiler Standalone Application MATLAB deployment targets MATLAB Compiler enables sharing MATLAB programs without integration programming MATLAB Compiler SDK provides implementation and platform flexibility for software developers MATLAB Production Server provides the most efficient development path for secure and scalable web and enterprise applications

MATLAB tutorial . School of Engineering . Brown University . To prepare for HW1, do sections 1-11.6 – you can do the rest later as needed . 1. What is MATLAB 2. Starting MATLAB 3. Basic MATLAB windows 4. Using the MATLAB command window 5. MATLAB help 6. MATLAB ‘Live Scripts’ (for

3. MATLAB script files 4. MATLAB arrays 5. MATLAB two‐dimensional and three‐dimensional plots 6. MATLAB used‐defined functions I 7. MATLAB relational operators, conditional statements, and selection structures I 8. MATLAB relational operators, conditional statements, and selection structures II 9. MATLAB loops 10. Summary

foundation of basic MATLAB applications in engineering problem solving, the book provides opportunities to explore advanced topics in application of MATLAB as a tool. An introduction to MATLAB basics is presented in Chapter 1. Chapter 1 also presents MATLAB commands. MATLAB is considered as the software of choice. MATLAB can be used .

I. Introduction to Programming Using MATLAB Chapter 1: Introduction to MATLAB 1.1 Getting into MATLAB 1.2 The MATLAB Desktop Environment 1.3 Variables and Assignment Statements 1.4 Expressions 1.5 Characters and Encoding 1.6 Vectors and Matrices Chapter 2: Introduction to MATLAB Programming 2.1 Algorithms 2.2 MATLAB Scripts 2.3 Input and Output

Compiler MATLAB Production Server Standalone Application MATLAB Compiler SDK Apps Files Custom Toolbox Python With MATLAB Users With People Who Do Not Have MATLAB.lib/.dll .exe . Pricing Risk Analytics Portfolio Optimization MATLAB Production Server MATLAB CompilerSDK Web Application