MATLAB Demystified PDF
Document Details
Uploaded by WellRunMars6038
Hazara University
2007
David McMahon
Tags
Summary
MATLAB Demystified is a textbook that provides a comprehensive introduction to the MATLAB environment, including topics such as vectors, matrices, plotting, statistics, solving algebraic equations and differential equations, and more. The book is aimed at professionals or students in various scientific disciplines.
Full Transcript
MATLAB® Demystified David McMahon New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto Copyright © 2007 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United States of Ame...
MATLAB® Demystified David McMahon New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto Copyright © 2007 by The McGraw-Hill Companies. All rights reserved. Manufactured in the United States of America. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher. 0-07-151030-3 The material in this eBook also appears in the print version of this title: 0-07-148551-1. All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. For more information, please contact George Hoare, Special Sales, at [email protected] or (212) 904-4069. TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior con- sent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMIT- ED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise. DOI: 10.1036/0071485511 Professional Want to learn more? We hope you enjoy this McGraw-Hill eBook! If you’d like more information about this book, its author, or related books and websites, please click here. This book is dedicated to my parents, who were gracious enough to put up with my taking so long to find my way in life For more information about this title, click here CONTENTS Preface ix Acknowledgments x CHAPTER 1 The MATLAB Environment 1 Overview of the User Interface 2 Command Window and Basic Arithmetic 3 The Assignment Operator 5 Basic Mathematical Definitions 9 Complex Numbers 11 Fixing Typos 12 Some File Basics 12 Ending Your MATLAB Session 14 Quiz 14 CHAPTER 2 Vectors and Matrices 15 Vectors 15 Creating Larger Vectors from Existing Variables 18 Creating Vectors with Uniformly Spaced Elements 18 Characterizing a Vector 20 Vector Dot and Cross Products 24 Referencing Vector Components 25 Basic Operations with Matrices 26 Matrix Multiplication 29 More Basic Operations 30 vi MATLAB Demystified Special Matrix Types 31 Referencing Matrix Elements 32 Finding Determinants and Solving Linear Systems 34 Finding the Rank of a Matrix 35 Finding the Inverse of a Matrix and the Pseudoinverse 39 Reduced Echelon Matrices 44 Matrix Decompositions 45 Quiz 47 CHAPTER 3 Plotting and Graphics 49 Basic 2D Plotting 49 More 2D Plotting Options 54 The Axis Commands 57 Showing Multiple Functions on One Plot 58 Adding Legends 60 Setting Colors 62 Setting Axis Scales 64 Subplots 67 Overlaying Plots and linspace 71 Polar and Logarithmic Plots 74 Plotting Discrete Data 79 Contour Plots 85 Three Dimensional Plots 90 Quiz 96 CHAPTER 4 Statistics and an Introduction to Programming in MATLAB 97 Generating Histograms 98 Basic Statistics 103 Writing Functions in MATLAB 106 Programming with For Loops 110 Calculating Standard Deviation and Median 110 More MATLAB Programming Tips 116 Quiz 119 Contents vii CHAPTER 5 Solving Algebraic Equations and Other Symbolic Tools 121 Solving Basic Algebraic Equations 121 Solving Quadratic Equations 123 Plotting Symbolic Equations 125 Solving Higher Order Equations 130 Systems of Equations 134 Expanding and Collecting Equations 135 Solving with Exponential and Log Functions 138 Series Representations of Functions 142 Quiz 144 CHAPTER 6 Basic Symbolic Calculus and Differential Equations 145 Calculating Limits 145 Computing Derivatives 153 The dsolve Command 161 Solving ODE’s 161 Systems of Equations and Phase Plane Plots 169 Quiz 178 CHAPTER 7 Numerical Solution of ODEs 179 Solving First Order Equations with ODE23 and ODE45 179 Solving Second Order Equations 188 Quiz 196 CHAPTER 8 Integration 197 The Int Command 197 Definite Integration 201 Multidimensional Integration 208 Numerical Integration 209 Quadrature Integration 216 Quiz 217 viii MATLAB Demystified CHAPTER 9 Transforms 219 The Laplace Transform 219 The Inverse Laplace Transform 222 Solving Differential Equations 227 Computing Fourier Transforms 232 Inverse Fourier Transforms 235 Fast Fourier Transforms 236 Quiz 239 CHAPTER 10 Curve Fitting 241 Fitting to a Linear Function 241 Fitting to an Exponential Function 257 Quiz 258 CHAPTER 11 Working with Special Functions 259 Gamma Functions 259 Bessel Functions 266 The Beta Function 274 Special Integrals 276 Legendre Functions 281 Airy Functions 284 Quiz 286 APPENDIX Bibliography and References 289 Final Exam 291 Answers to Quiz and Exam Questions 303 Index 319 ABOUT THE AUTHOR David McMahon, Ph.D., is a physicist and researcher at Sandia National Laboratories. He is the author of Linear Algebra Demystified, Quantum Mechanics Demystified, Relativity Demystified, Signals and Systems Demystified, and Statics and Dynamics Demystified. Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. PREFACE MATLAB is one of the most widely used computational tools in science and engineering. No matter what your background—be it physics, chemistry, math, or engineering—it would behoove you to at least learn the basics of this powerful tool. There are three good reasons to learn a computational mathematics tool. The first is that it serves as a background check for work you might be doing by hand. If you are a student, it’s nice to have a back up that you can use to check your answers. I advise that you don’t become co-dependent on a computational tool or trust it as though it were an Oracle. Do your work by hand when requested by your professors and just use MATLAB or any other tool to check your work to make sure it’s correct. The second reason is having a tool like MATLAB is priceless for generating plots and for doing numerical methods. Instead of having to go through a tedious process of plotting something by hand you can just have MATLAB generate any nice plot you desire. Thirdly, the bottom line is that at some point in your career you will have to use a computational mathematics tool. If you’re a professor doing theoretical work, at one point or another you are going to be working on a project where analytical solutions are not possible. If you work in industry or in a national lab, chances are the work you’re doing can’t be done by hand and will require a numerical solution. MATLAB is widely used in universities, in national laboratories and at private companies. Knowing MATLAB will definitely be a plus on your resume. Now a word about this particular book. This book is aimed squarely at the MATLAB beginner. The purpose is not to wow experts with complicated solutions built with MATLAB. Rather, the purpose of this book is to introduce a person new to MATLAB to the world of computational mathematics. The approach taken here is to set about learning how to use MATLAB to do some basic things-plot functions, solve algebraic equations, compute integrals and solve differential equations for example. So the examples we present in this book are going to be simple and aimed at the novice. If you have never touched MATLAB before or are having lot’s of trouble with it, this book will help you build a basic skill set that can be used to master it. The book is a stepping stone to mastery and nothing more. Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. ACKNOWLEDGMENTS I would like to thank Rayjan Wilson for his thorough and thoughtful review of this manuscript. His insightful comments and detailed review were vital to making this manuscript a success. Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. CHAPTER 1 The MATLAB Environment We begin our tour of MATLAB by considering the basic structure of the user inter- face. We’ll learn how to enter commands, create files, and do other sorts of mun- dane tasks that we’ll need to know before we can tackle solving mathematics prob- lems. The elements covered in this chapter will be used throughout the book and indeed throughout the lifetime of your MATLAB use. In this book we are going to cover a core bit of knowledge about MATLAB to get you started using it. Our approach in this book is to take a few small bites in each chapter so that you can learn how to do a few important tasks at a time. At the end of the book you won’t be a MATLAB expert, but you’ll be on your way to getting comfortable with it and will know how to accomplish lots of common tasks, helping you make progress in your class at school or making it easier to grab a thick hard-to-read MATLAB book at the office so you can do real computing. Anyway, let’s begin by considering the main MATLAB screen you see when you start the program. Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. 2 MATLAB Demystified Overview of the User Interface In this book we will assume that you are using Windows, although that won’t be relevant for the most part. Please note that we will be using MATLAB version 7.1 in this book. MATLAB is started just like any other Windows program. Just go to your program files menu and search for the MATLAB folder. When you click on it, you will see several options depending on your installation, but you will have at least the following three options MATLAB (version number) M-file editor Uninstaller To start the program, you select MATLAB (7.1). The default MATLAB desktop will then open on your screen (see Figure 1-1). As shown in the figure, the screen is divided into three main elements. These are File listing in the current directory Figure 1-1 The MATLAB desktop CHAPTER 1 The MATLAB Environment 3 Command History Window Command Window The standard mix of menus appears on the top of the MATLAB desktop that allows you to do things like file management and debugging of files you create. You will also notice a drop-down list on the upper right side of the desktop that allows you to select a directory to work in. The most important item of business right now is the Command Window. Command Window and Basic Arithmetic The Command Window is found on the right-hand side of the MATLAB desktop. Commands are entered at the prompt with looks like two successive “greater than” signs: >> Let’s start by entering a few really basic commands. If you want to find the value of a numerical expression, simply type it in. Let’s say we want to know the value of 433.12 multiplied by 15.7. We type 433.12 * 15.7 at the MATLAB prompt and hit the enter key. The result looks like this: >> 433.12*15.7 ans = 6.8000e+003 MATLAB spits out the answer to our query conveniently named ans. This is a variable or symbolic name that can be used to represent the value later. Chances are we will wish to use our own variable names. So for example, we might want to call a variable x. Suppose we want to set it equal to five multiplied by six. To do this, we type the input as >> x=5*6 x = 30 Once a variable has been entered into the system, we can refer to it later. Suppose that we want to compute a new quantity that we’ll call y, which is equal to x multiplied by 3.56. Then we type >> y = x * 3.56 y = 106.8000 4 MATLAB Demystified Now, you will notice that in this example we put spaces in between each term in our equation. This was only done to enhance the readability and professional appearance of our output. MATLAB does not require you to include these spaces in your input. We could just as well type y = x * 3.56 as y = x * 3.56; however, the latter presentation is cleaner and easier to read. When your expressions get complicated, it will be more important to keep things neat so it’s advisable to include the spaces. Let’s summarize basic arithmetical input in MATLAB. To write the multiplication ab, in MATLAB we type a * b a For division, the quantity is typed as b a / b This type of division is referred to as right division. MATLAB also allows another way to enter division, called left division. We can enter the quantity ba by typing the slash mark used for division in the opposite way, that is, we use a back slash instead of a forward slash a \ b Exponentiation ab is entered in the following way a ^ b Finally, addition and subtraction are entered in the usual way a + b a – b The precedence followed in mathematical operations by MATLAB is the same used in standard mathematics, but with the following caveat for left and right division. That is, exponentiation takes precedence over multiplication and division, which fall on equal footing. Right division takes precedence over left division. Finally, addition and subtraction have the lowest precedence in MATLAB. To override precedence, enclose expression in parentheses. EXAMPLE 1-1 Use MATLAB to evaluate ⎛ 3⎞ 9 ⎡3 9 ⎤ 5 ⎜ ⎟ + and 4 3 ⎢ + ⎝ 4⎠ 5 ⎣ 4 ( 2 )3⎥⎦ CHAPTER 1 The MATLAB Environment 5 SOLUTION 1-1 The command required to find the value of the first expression is >> 5*(3/4) + 9/5 ans = 5.5500 For the second expression, we use some parentheses along with the exponentiation operator a ^ b. Although this is a simple expression, let’s enter it in pieces to get used to using variables. We obtain >> r = 4^3 r = 64 >> s = 3/4 + 9/(2*3) s = 2.2500 >> t=r*s t = 144 The Assignment Operator The equals sign “=” is known as the assignment operator. While it does what you think it does much of the time, that is, describes an equation, at other times in MATLAB it’s more appropriate to think of it as an instruction to assign a value to a variable the way you would in a computer program. The distinction between the two interpretations can be illustrated in the following way. If you type x + 6 = 90 in MATLAB, you get the following response ??? x+6=90 Error: The expression to the left of the equals sign is not a valid target for an assignment. So while the expression is a completely valid equation you could write down if doing algebra on paper, MATLAB doesn’t know what to do with it. On the other hand, MATLAB is completely happy if you assign the value 90 – 6 to the variable x by writing x = 90 – 6 6 MATLAB Demystified Another way that the assignment operator works more like an assignment in a computer program is in a recursive type assignment to a variable. That is, MATLAB allows you to write x = x + 4 if we have previously defined the variable x. For example, the following sequence is completely valid >> x = 34^2 x = 1156 >> x = x + 4 x = 1160 To use a variable on the right-hand side of the assignment operator, we must assign a value to it beforehand. So while the following command sequence will generate an error >> x = 2 x = 2 >> t = x + a ??? Undefined function or variable 'a'. The following sequence does not >> x = 2 x = 2 >> a = 3.5 a = 3.5000 >> t = x + a t = 5.5000 In many instances, it is not desirable to have MATLAB spit out the result of an assignment. To suppress MATLAB output for an expression, simply add a semicolon (;) after the expression. In the following command sequence, first we just type in the assignment x = 3. MATLAB duly reports this back to us. On the next line, we enter x = 3; so that MATLAB does not waste space by telling us something we already know. Instead it comes back with the command prompt waiting for our next input: >> x = 3 x = 3 CHAPTER 1 The MATLAB Environment 7 >> x = 3; >> We can include multiple assignments on the same line. For example, the following expressions are valid >> x = 2; y = 4; z = x*y z = 8 Notice the two semicolons, they tell MATLAB we don’t want to see the values of x and y. When doing a lot of calculations, you may end up with a large number of variables. You can refresh your memory by typing who in the MATLAB command window. Doing this will tell MATLAB to display all of the variable names you have used up to this point. For instance, in our case we have >> who Your variables are: V a ans r s t x y z By typing whos, we get a bit more information. This will tell us the variables currently in memory, their type, how much memory is allocated to each variable, and whether or not they are complex (see below). In our case we have >> whos Name Size Bytes Class V 1x1 8 double array a 1x1 8 double array ans 1x1 16 double array (complex) r 1x1 8 double array s 1x1 8 double array t 1x1 8 double array x 1x1 8 double array y 1x1 8 double array z 1x1 8 double array Grand total is 9 elements using 80 bytes Now suppose we want to start all over. We can do this by issuing a clear command. Clear can be applied globally by simply typing clear and then hitting the enter key, or to specific variables by typing clear followed by a space delimited variable list. If we wanted to reset or clear the variables x, y, and z that we have been using, then we could type clear x y z 8 MATLAB Demystified MATLAB will simply return the command prompt and won’t say anything else, but if you try to use these variables again without assigning them values it will be as if they had not been seen before. Long assignments can be extended to another line by typing an ellipsis which is just three periods in a row. For example >> FirstClassHolders = 72; >> Coach = 121; >> Crew = 8; >> TotalPeopleOnPlane = FirstClassHolders + Coach... + Crew TotalPeopleOnPlane = 201 The ellipsis follows Coach on the line used to define TotalPeopleOnPlane. After you type the ellipsis, just hit the enter key. MATLAB will move to the following line awaiting further input. OK, something you are probably wondering, as I was when I started using MATLAB, was how in the world do you control the way numbers are displayed on the screen? So far in our examples, MATLAB has been spitting out numbers with four decimal places. This is known as short format in MATLAB. It’s the default in MATLAB and if that’s all the precision you require, then you don’t have to do anything. If you want more, then you can tell MATLAB to add more digits to the right of the decimal point by using the format command. If we want 16 digits instead of 4, we type format long. To see how this works, look at the following calculation, displayed in both formats >> format long >> x = 3 + 11/16 + 2^1.2 x = 5.98489670999407 >> format short >> x = 3 + 11/16 + 2^1.2 x = 5.9849 Comparing the long and short formats, notice that the fourth decimal place was rounded up to nine when format short was used. If you want to do financial calculations, you can use the format bank command. As expected, this rounds everything off to two decimal places. >> format bank >> hourly = 35.55 CHAPTER 1 The MATLAB Environment 9 hourly = 35.55 >> weekly = hourly*40 weekly = 1422.00 MATLAB displays large numbers using exponential notation. That is it represents 5.4387 × 103 as 5.4387e + 003. If you want all numbers to be represented in this fashion, you can do so. This type of notation can also be defined using the short or long formats. For short (four decimal places plus the exponent) you can type format short e. To allow 15 decimal digits plus the exponent, type format long e. Here is an example of the short exponent format >> format short e >> 7.2*3.1 ans = 2.2320e+001 If you type format rat, then MATLAB will find the closest rational expression it can that corresponds to the result of a calculation. Pretty neat tool huh? Let’s repeat the previous calculation >> format rat >> 7.2*3.1 ans = 558/25 Basic Mathematical Definitions MATLAB comes with many basic or familiar mathematical quantities and functions built in. Let’s show how to use π in an example. EXAMPLE 1-2 Find the volume of a sphere of radius 2 m. SOLUTION 1-2 The volume of a sphere is given by 4 V= π R3 3 10 MATLAB Demystified Of course MATLAB comes with π predefined. To use it, we just type pi. So after defining a variable to hold the radius, we can find the volume by typing >> r = 2; >> V = (4/3) *pi*r^3 V = 33.5103 Another famous number that shows up in many mathematical applications is the exponential function. That is, e ≈ 2.718. We can reference e in MATLAB by typing exp(a) which gives us the value of ea. Here are a few quick examples >> exp(1) ans = 2.7183 >> exp(2) ans = 7.3891 To find the square root of a number, we type sqrt. For example >> x = sqrt(9) x = 3 >> y = sqrt(11) y = 3.3166 To find the natural log of a number x, type log(x). >> log(3.2) ans = 1.1632 >> x = 5; log(5) ans = 1.6094 If you want the base ten logarithm, type log10(x) >> x = 3; log10(x) ans = 0.4771 MATLAB comes equipped with the basic trig functions and their inverses, taking radian argument by default. These are typed in lower case using the standard notation. For instance CHAPTER 1 The MATLAB Environment 11 >> cos(pi/4) ans = 0.7071 To use an inverse of a trig function, add on an a before the name of the trig function. For example, to compute the inverse tangent of a number we can use the following >> format rat >> atan(pi/3) ans = 1110/1373 Complex Numbers We can also enter complex numbers in MATLAB. To remind members of our audience who are Aggie graduates, the square root of –1 is defined as i = −1 A complex number is one that can be written in the form z = x +iy, where x is the real part of z and y is the imaginary part of z. It is easy to enter complex numbers in MATLAB, by default it recognizes i as the square root of minus one. We can do calculations with complex numbers in MATLAB pretty easily. For example a = 2 +3i b = 1 − i ⇒ a + b = 3 + 2i Let’s verify this in MATLAB. It is not necessary to add spaces or include a multiplication symbol (*) when typing i in MATLAB. >> format short >> a = 2 + 3i; >> b = 1 - i; >> c = a + b c = 3.0000 + 2.0000i 12 MATLAB Demystified Fixing Typos It’s going to be a fact that now and then you are going to type in an expression with an error. If you hit the enter key and then later realize what happened, it’s not necessary to retype the line. Just use your arrow keys to move back up to the offending line. Fix your error, and then hit enter again and MATLAB will correct the output. Some File Basics Let’s round out the chapter by considering some basic operations with files. MATLAB wouldn’t be that useful if you couldn’t save and retrieve your work right? Let’s say you want to save all the expressions and variables you have entered in the command window for use at a later time. You can do this by executing the following actions: 1. Click on the File pull-down menu 2. Select Save Workspace As… 3. Type in a file name 4. Click on the Save button This method creates a MATLAB file which has a.MAT file extension in Windows. If you save a file this way, you can retrieve all the commands in it and work with it again just like you can when working with files in any other computer program. Sometimes, especially when working on complicated projects, you won’t want to sit there and type every expression in a command window. It might be more appropriate to type a long sequence of operations and store them in a file that can be executed with a single command in the command window. This is done by creating a script file. This type of file is known as a MATLAB program and is saved in a file format with a.M extension. For this reason, we also call them M-files. We can also create M-files that are function files. From what we’ve done so far, you already know how to create a script file. All a script file comes down to is a saved sequence of MATLAB commands. Let’s create a simple script file that will compute ex for a few values of x. First, open the MATLAB editor. Either Click New → M-File under the File pull-down menu Or click on the New File icon on our toolbar at the top of the screen CHAPTER 1 The MATLAB Environment 13 Now type in the following lines: % script file example1.m to compute exponential of a set of numbers x = [1:2:3:4]; y = exp(x) Notice the first line begins with a % sign. This line is a comment. This is a line of text that is there for our benefit, it’s a descriptive note that MATLAB ignores. The next line creates an array or set of numbers. An array is denoted using square braces [] and by delimiting the elements of the array with colons or commas. The final line will tell MATLAB to calculate the exponential of each member of the array, in other words the values e1, e2, e3, e4. Save the file by clicking the Save icon in the file editor or by selecting Save As from the File pull-down menu. Save the file as example1.m in your MATLAB directory. Now return to the MATLAB desktop command window. Type in example1. If you did everything right, then you will see the following output >> example1 y = 2.7183 7.3891 20.0855 54.5982 We can also use M-files to create and store data. Following an example from another McGraw-Hill book on MATLAB, let’s create a set of temperatures that we will store in a file. We do this by creating a list of temperatures in the file editor temps = [32,50,65,70,85] Now we save this as a file that we’ll call TemperatureData.m. We store this file in the MATLAB directory. To access it in the command window, we just type the name of the file. MATLAB responds by spitting out the list of numbers: >> TemperatureData temps = 32 50 65 70 85 Now we can use the data by referring to the array name used in the file. Let’s create another set of numbers called Celsius that converts these familiar temps into the European style Celsius temperatures we are so familiar with. This can be done with the following command >> CelsiusTemps = (5/9) * (temps - 32) CelsiusTemps = 0 10.0000 18.3333 21.1111 29.4444 Later, we will investigate programming in MATLAB and we will show you how to create functions that can be called later in the command window. 14 MATLAB Demystified Ending Your MATLAB Session OK we have gotten started with a few very basic MATLAB commands. You might want to save your work and then shut down MATLAB. How do you get it off your screen? Well you can end your MATLAB session by selecting exit from the File pull-down menu, just like you would with any other program. Optionally, you can type quit in the command window and MATLAB will close. Quiz Use MATLAB to calculate the following quantities: 11 1. 5 14 8 2. 5 + 37 3 3. 91.25 4. True or False. If y has not been assigned a value, MATLAB will allow you to define the equation x = y ^2 to store in memory for later use. 5. If the volume of a cylinder of height h and radius r is given by V = πr2h, use MATLAB to find the volume enclosed by a cylinder that is 12 cm high with a diameter of 4 cm. 6. Use MATLAB to compute the sin of π/3 expressed as a rational number. 7. Create a MATLAB m file to display the results of sin(π/4), sin(π/3), sin(π/2) as rational numbers. CHAPTER 2 Vectors and Matrices One area where MATLAB is particularly useful is in the computer implementation of linear algebra problems. This is because MATLAB has exceptional capabilities for handling arrays of numbers, making it a useful tool for many scientific and engineering applications. Vectors A vector is a one-dimensional array of numbers. MATLAB allows you to create column vectors or row vectors. A column vector can be created in MATLAB by enclosing a set of semicolon delimited numbers in square brackets. Vectors can have any number of elements. For example, to create a column vector with three elements we write: >> a = [2; 1; 4] a = 2 1 4 Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. 16 MATLAB Demystified Basic operations on column vectors can be executed by referencing the variable name used to create them. If we multiply a column vector by a number, this is called scalar multiplication. Suppose that we wanted to create a new vector such that its components were three times the components in the vector a we just created above. We could start by defining a scalar variable (remember that a semicolon after a command suppresses the output): >> c = 3; Next, we just perform the operation treating a like another variable: >> b = c*a b = 6 3 12 To create a row vector, we enclose a set of numbers in square brackets but this time use a space or comma to delimit the numbers. For example: >> v = [2 0 4] v = 2 0 4 Or using commas: >> w = [1,1,9] w = 1 1 9 Column vectors can be turned into row vectors and vice versa using the transpose operation. Suppose that we have a column vector with n elements denoted by: ⎡v1 ⎤ ⎢v ⎥ v = ⎢ 2⎥ ⎢M ⎥ ⎢⎣vn ⎥⎦ Then the transpose is given by: vT = ⎡⎣v1 v2 L vn ⎤⎦ CHAPTER 2 Vectors and Matrices 17 In MATLAB, we represent the transpose operation with a single quote or tickmark (‘). Taking the transpose of a column vector produces a row vector: >> a = [2; 1; 4]; >> y = a' y = 2 1 4 Now let’s take the transpose of a row vector to produce a column vector: >> Q = [2 1 3] Q = 2 1 3 >> R = Q' R = 2 1 3 It is also possible to add or subtract two vectors to produce another. In order to perform this operation the vectors must both be of the same type and the same length, so we can add two column vectors together to produce a new column vector or we can add two row vectors to produce a new row vector, for example. This can be done referencing the variables only, it is not necessary for the user to list the components. For example, let’s add two column vectors together: >> A = [1; 4; 5]; >> B = [2; 3; 3]; >> C = A + B C = 3 7 8 Now let’s subtract one row vector from another: >> W = [3,0,3]; >> X = [2,1,1]; >> Y = W – X Y = 1 –1 2 18 MATLAB Demystified Creating Larger Vectors from Existing Variables MATLAB allows you to append vectors together to create new ones. Let u and v be two column vectors with m and n elements respectively that we have created in MATLAB. We can create a third vector w whose first m elements are the elements of u and whose next n elements are the elements of v. The newly created column vector has m + n elements. This is done by writing w = [u; v]. For example: >> A = [1; 4; 5]; >> B = [2; 3; 3]; >> D = [A;B] D = 1 4 5 2 3 3 This can also be done using row vectors. To create a row vector u with m + n elements from a vector r with m elements and a vector s with n elements, we write u = [r, s]. For example: >> R = [12, 11, 9] >> S = [1, 4]; >> T = [R, S] T = 12 11 9 1 4 Creating Vectors with Uniformly Spaced Elements It is possible to create a vector with elements that are uniformly spaced by an increment q, where q is any real number. To create a vector x with uniformly spaced elements where xi is the first element and xe is the final element, the syntax is: x = [xi : q : xe] CHAPTER 2 Vectors and Matrices 19 For example, we can create a list of even numbers from 0 to 10 by writing: >> x = [0:2:10] x = 0 2 4 6 8 10 We have already been using this technique in the last chapter to create a list of values for plotting purposes. Let’s see how this works behind the scenes by looking at some vectors with a small number of elements. First we create a set of x values: >> x = [0:0.1:1] x = Columns 1 through 10 0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000 0.7000 0.8000 0.9000 Column 11 1.0000 The set of x values can be used to create a list of points representing the values of some given function. For example, suppose that y = ex. Then we have: >> y = exp(x) y = Columns 1 through 10 1.0000 1.1052 1.2214 1.3499 1.4918 1.6487 1.8221 2.0138 2.2255 2.4596 Column 11 2.7183 Or we could have y = x2 : >> y = x^2 y = Columns 1 through 10 0 0.0100 0.0400 0.0900 0.1600 0.2500 0.3600 0.4900 0.6400 0.8100 Column 11 1.0000 20 MATLAB Demystified An aside—note that when squaring a vector in MATLAB, a period must precede the power operator (^). If we just enter >> y = x^2, MATLAB gives us an error message: ??? Error using ==> mpower Matrix must be square. Returning to the process of creating an array of uniformly spaced elements, be aware that you can also use a negative increment. For instance, let’s create a list of numbers from 100 to 80 decreasing by 5: >> u = [100:–5:80] u = 100 95 90 85 80 When looking at plotting we have also seen how to create a row vector with elements from a to b with n regularly spaced elements using the linspace command. To review, linspace(a,b) creates a row vector of 100 regularly spaced elements between a and b, while linspace(a,b,n) creates a row vector of n regularly spaced elements between a and b. In both cases MATLAB determines the increment in order to have the correct number of elements. MATLAB also allows you to create a row vector of n logarithmically spaced elements by typing logspace(a,b,n) a b This creates n regularly spaced elements between 10 and 10. For example: >> logspace(1,2,5) ans = 10.0000 17.7828 31.6228 56.2341 100.0000 Or another example: >> logspace(–1,1,6) ans = 0.1000 0.2512 0.6310 1.5849 3.9811 10.0000 Characterizing a Vector The length command returns the number of elements that a vector contains. For example: CHAPTER 2 Vectors and Matrices 21 >> A = [2;3;3;4;5]; >> length(A) ans = 5 >> B = [1;1]; >> length(B) ans = 2 The length command can be applied to row and column vectors (see “Basic Operations with Matrices”, later in this chapter) and, as we will see below, to matrices. We can find the largest and smallest elements in a vector using the max and min commands. For example: >> A = [8 4 4 1 7 11 2 0]; >> max(A) ans = 11 >> min(A) ans = 0 To find the magnitude of a vector we can employ two operations. Recall that the magnitude of a vector ⎡v1 ⎤ ⎢v ⎥ v = ⎢ 2⎥ ⎢M ⎥ ⎢⎣vn ⎥⎦ is given by: v = v12 + v22 + L vn2 To perform this operation, we will first take the dot product of a vector with itself. This is done by using array multiplication (.*). First let’s define a vector: >> J = [0; 3; 4]; Now we can do array multiplication: >> J.*J ans = 22 MATLAB Demystified 0 9 16 This produces a vector whose elements are v21, v22,…. To get the summation we need, we can use the sum operator: >> a = sum(J.*J) a = 25 Then the magnitude of the vector is the square root of this quantity: >> mag = sqrt(a) mag = 5 If a vector contains complex numbers, then more care must be taken when computing the magnitude. When computing the row vector, we must compute the complex conjugate transpose of the original vector. For example, if: ⎡ i ⎤ u = ⎢1 + 2i⎥ ⎢ ⎥ ⎣ 4 ⎦ Then to compute the magnitude, we need the following vector: u† = [−i 1−2i 4] Then the summation we need to compute is: ⎡ i ⎤ u u = [−i 1 − 2i 4] ⎢1 + 2i⎥ = ( −i )(i ) + (1 − 2i )(1 + 2i ) + (4)(4) = 22 † ⎢ ⎥ ⎣ 4 ⎦ Hence the magnitude of a vector with complex elements is: u = u †u = 22 You can see how using the complex conjugate transpose when computing our sum ensures that the magnitude of the vector will be real. Now let’s see how to do this in MATLAB. First let’s enter this column vector: >> u = [i; 1 + 2i; 4]; CHAPTER 2 Vectors and Matrices 23 If we just compute the sum of the vector multiplication as we did in the previous example, we get a complex number that won’t work: >> sum(u.*u) ans = 12. So let’s define another vector which is the complex conjugate transpose of u. MATLAB does this automatically with the transpose operator: >> v = u' v = 0 – 1.0000i 1.0000 – 2.0000i 4.0000 Now we can perform our sum: >> b = sum(v.*u) ??? Error using ==> times Matrix dimensions must agree. Unfortunately it looks like we’ve been led down a blind alley! It appears there isn’t quite a one to one correspondence to what we would do on paper. How can we get around this? Let’s just compute the complex conjugate of the vector, and form the sum. We can get the complex conjugate of a vector with the conj command: >> v = conj(u) v = 0 – 1.0000i 1.0000 – 2.0000i 4.0000 Now we obtain the correct answer, and can get the magnitude: >> b = sum(v.*u) b = 22 >> magu = sqrt(b) magu = 4.6904 Of course this could all be done in one step by writing: >> c = sqrt(sum(conj(u).*u)) c = 4.6904 24 MATLAB Demystified Here we are actually doing things the hard way—just to illustrate the method and some MATLAB commands. In the next section we will see how to compute the magnitude of a vector automatically. We can use the abs command to return the absolute value of a vector, which is a vector whose elements are the absolute values of the elements in the original vector, i.e.: >> A = [–2 0 –1 9] >> B = abs(A) B = 2 0 1 9 Vector Dot and Cross Products The dot product between two vectors A = (a1 a2 … an) and B = (b1 b2 … bn) is given by A ⋅ B = ∑ ai bi i In MATLAB, the dot product of two vectors a, b can be calculated using the dot(a,b) command. The dot product between two vectors is a scalar, i.e. it’s just a number. Let’s compute a simple example using MATLAB: >> a = [1;4;7]; b = [2;–1;5]; >> c = dot(a,b) c = 33 The dot product can be used to calculate the magnitude of a vector. All that needs to be done is to pass the same vector to both arguments. Consider the vector in the last section: >> J = [0; 3; 4]; Calling dot we obtain: >> dot(J,J) ans = 25 CHAPTER 2 Vectors and Matrices 25 Or we can calculate the magnitude of the vector this way: >> mag = sqrt(dot(J,J)) mag = 5 The dot operation works correctly with vectors that contain complex elements: >> u = [–i; 1 + i; 4 + 4*i]; >> dot(u,u) ans = 35 Another important operation involving vectors is the cross product. To compute the cross product, the vectors must be three dimensional. For example: >> A = [1 2 3]; B = [2 3 4]; >> C = cross(A,B) C = –1 2 –1 Referencing Vector Components MATLAB has several techniques that can be used to reference one or more of the components of a vector. The ith component of a vector v can be referenced by writing v(i). For example: >> A = [12; 17; –2; 0; 4; 4; 11; 19; 27]; >> A(2) ans = 17 >> A(8) ans = 19 Referencing the vector with a colon, such as v(:); tells MATLAB to list all of the components of the vector: >> A(:) ans = 12 17 26 MATLAB Demystified –2 0 4 4 11 19 27 We can also pick out a range of elements out of a vector. The example we’ve been working with so far in this section is a vector A with nine components. We can reference components four to six by writing A(4:6) and use these to create a new vector with three components: >> v = A(4:6) v = 0 4 4 In the next section, we will see how these techniques can be used to reference the columns or rows in an array of numbers called a matrix. Basic Operations with Matrices A matrix is a two-dimensional array of numbers. To create a matrix in MATLAB, we enter each row as a sequence of comma or space delimited numbers, and then use semicolons to mark the end of each row. For example, consider: ⎡−1 6 ⎤ A=⎢ ⎣ 7 11⎥⎦ This matrix is entered in MATLAB using the following syntax: >> A = [–1,6; 7, 11]; Or consider the matrix: ⎡ 2 0 1⎤ B = ⎢−1 7 4⎥ ⎢ ⎥ ⎣ 3 0 1⎦ CHAPTER 2 Vectors and Matrices 27 We enter it in MATLAB in the following way: >> B = [2,0,1;–1,7,4; 3,0,1] Many of the operations that we have been using on vectors can be extended for use with matrices. After all a column vector with n elements is just a matrix with one column and n rows while a row vector with n elements is just a matrix with one row and n columns. For example, scalar multiplication can be carried out referencing the name of the matrix: >> A = [–2 2; 4 1] A = –2 2 4 1 >> C = 2*A C = –4 4 8 2 If two matrices have the same number of rows and columns, we can add and subtract them: >> A = [5 1; 0 9]; >> B = [2 –2; 1 1]; >> A + B ans = 7 –1 1 10 >> A – B ans = 3 3 –1 8 We can also compute the transpose of a matrix. The transpose operation switches the rows and columns in a matrix, for example: ⎡−1 2 4⎤ ⎡−1 0 2⎤ ⎢ ⎥ A = 0 1 6 , ⇒ A = ⎢ 2 1 7⎥ T ⎢ ⎥ ⎢ ⎥ ⎣ 2 7 1⎦ ⎣ 4 6 1⎦ 28 MATLAB Demystified We can take the transpose of a matrix using the same notation used to calculate the transpose of a vector: >> A = [–1 2 0; 6 4 1] A = –1 2 0 6 4 1 >> B = A' B = –1 6 2 4 0 1 If the matrix contains complex elements, the transpose operation will compute the conjugates: >> C = [1 + i, 4 – i; 5 + 2*i, 3 – 3*i] C = 1.0000 + 1.0000i 4.0000 – 1.0000i 5.0000 + 2.0000i 3.0000 – 3.0000i >> D = C' D = 1.0000 – 1.0000i 5.0000 – 2.0000i 4.0000 + 1.0000i 3.0000 + 3.0000i If we want to compute the transpose of a matrix with complex elements without computing the conjugate, we use (.’): >> D = C' D = 1.0000 + 1.0000i 5.0000 + 2.0000i 4.0000 – 1.0000i 3.0000 – 3.0000i We can perform array multiplication. It is important to recognize that this is not matrix multiplication. We use the same notation used when multiplying two vectors together (.*). For example: >> A = [12 3; –1 6]; B = [4 2; 9 1]; >> C = A.*B C = 48 6 –9 6 CHAPTER 2 Vectors and Matrices 29 As you can see, what the operation A. *B does is it performs component by component multiplication. Abstractly it works as follows: ⎛a a12 ⎞ ⎛ b11 b12 ⎞ ⎛ ( a11 )( b11 ) ( a12 )( b12 )⎞ A. * B = ⎜ 11 = ⎝ a21 a22⎟⎠ ⎜⎝ b21 b22⎟⎠ ⎜⎝( a21 )( b21 ) ( a22 )( b22 )⎟⎠ We see how to perform matrix multiplication in the next section. Matrix Multiplication Consider two matrices A and B. If A is an m × p matrix and B is a p × n matrix, they can be multiplied together to produce an m × n matrix. To do this in MATLAB, we leave out the period (.) and simply write A*B. Keep in mind that if the dimensions of the two matrices are not correct, the operation will generate an error. Let’s consider two matrices: ⎛ 2 1⎞ ⎛3 4⎞ A=⎜ ⎟ , B=⎜ ⎝ 1 2⎠ ⎝5 6⎟⎠ These are both 2 × 2 matrices, so matrix multiplication is permissible. First, let’s do array multiplication so we can see the difference: >> A = [2 1; 1 2]; B = [3 4; 5 6]; >> A.*B ans = 6 4 5 12 Now we leave out the ‘.’ character and execute matrix multiplication, which produces quite a different answer: >> A*B ans = 11 14 13 16 30 MATLAB Demystified Here is another example. Consider: ⎛ 1 4⎞ ⎛ −1 7 4 ⎞ A = ⎜ 8 0⎟ , B = ⎜ ⎜⎝ −1 3⎟⎠ ⎝ 2 1 −2⎟⎠ The matrix A is a 3 × 2 matrix, while B is a 2 × 3 matrix. Since the number of columns of A matches the number of rows of B, we can calculate the product AB. In MATLAB: >> A = [1 4; 8 0; –1 3]; B = [–1 7 4; 2 1 –2]; >> C = A*B C = 7 11 –4 –8 56 32 7 –4 –10 While matrix multiplication is possible in this case, array multiplication is not. To use array multiplication, both row and column dimensions must agree for each array. Here is what MATLAB tells us: >> A.*B ??? Error using ==> times Matrix dimensions must agree. More Basic Operations MATLAB also allows several operations on matrices that you might not be immediately used to from your linear algebra background. For example, MATLAB allows you to add a scalar to an array (vector or matrix). This operation works by adding the value of the scalar to each component of the array. Here is how it works with a row vector: >> A = [1 2 3 4]; >> b = 2; >> C = b + A C = 3 4 5 6 CHAPTER 2 Vectors and Matrices 31 We can also perform left and right division on an array. This works by matching component by component, so the arrays have to be of the same size. For example, we tell MATLAB to perform array right division by typing (./ ): A = [2 4 6 8]; B = [2 2 3 1]; >> C = A./B C = 1 2 2 8 Array left division is indicated by writing C = A.\B (this is the same as C = B./A): >> C = A.\B C = 1.0000 0.5000 0.5000 0.1250 Basically any mathematical operation you can think of can be implemented in MATLAB with arrays. For instance, we can square each of the elements: >> B = [2 4; –1 6] B = 2 4 –1 6 >> B.^2 ans = 4 16 1 36 Special Matrix Types The identity matrix is a square matrix that has ones along the diagonal and zeros elsewhere. To create an n × n identity matrix, type the following MATLAB command: eye(n) Let’s create a 4 × 4 identity matrix: >> eye(4) ans = 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 32 MATLAB Demystified To create an n × n matrix of zeros, we type zeros(n). We can also create a m × n matrix of zeros by typing zeros(m,n). It is also possible to generate a matrix completely filled with 1’s. Surprisingly, this is done by typing ones(n) or ones(m,n) to create n × n and m × n matrices filled with 1’s, respectively. Referencing Matrix Elements Individual elements and columns in a matrix can be referenced using MATLAB. Consider the matrix: >> A = [1 2 3; 4 5 6; 7 8 9] A = 1 2 3 4 5 6 7 8 9 We can pick out the element at row position m and column position n by typing A(m,n). For example: >> A(2,3) ans = 6 To reference all the elements in the ith column we write A(:,i). For example, we can pick out the second column of A: >> A(:,2) ans = 2 5 8 To pick out the elements in the ith through jth columns we type A(:,i:j). Here we return the second and third columns: >> A(:,2:3) ans = 2 3 5 6 8 9 CHAPTER 2 Vectors and Matrices 33 We can pick out pieces or submatrices as well. Continuing with the same matrix, to pick out the elements in the second and third rows that are also in the first and second columns, we write: >> A(2:3,1:2) ans = 4 5 7 8 We can change the value of matrix elements using these references as well. Let’s change the element in row 1 and column 1 to –8: >> A(1,1) = –8 A = –8 2 3 4 5 6 7 8 9 To create an empty array in MATLAB, simply type an empty set of square braces []. This can be used to delete a row or column in a matrix. Let’s delete the second row of A: >> A(2,:)=[] A = –8 2 3 7 8 9 This has turned the formerly 3 × 3 matrix into a 2 × 3 matrix. It’s also possible to reference rows and columns in a matrix and use them to create new matrices. In this example, we copy the first row of A four times to create a new matrix: >> E = A([1,1,1,1],:) E = –8 2 3 –8 2 3 –8 2 3 –8 2 3 This example creates a matrix out of both rows of A: >> F = A([1,2,1],:) F = –8 2 3 7 8 9 –8 2 3 34 MATLAB Demystified Finding Determinants and Solving Linear Systems The determinant of a square matrix is a number. For a 2 × 2 matrix, the determinant is given by: a11 a12 D= = a11a22 − a12 a21 a21 a22 To calculate the determinant of a matrix A in MATLAB, simply write det(A). Here is the determinant of a 2 × 2 matrix: >> A = [1 3; 4 5]; >> det(A) ans = –7 In this example, we find the determinant of a 4 × 4 matrix: >> B = [3 –1 2 4; 0 2 1 8; –9 17 11 3; 1 2 3 –3]; >> det(B) ans = –533 Needless to say, such a calculation would be extremely tedious by hand. Determinants can be used to find out if a linear system of equations has a solution. Consider the following set of equations: 5x + 2y − 9z = 44 −9x − 2y + 2z = 11 6x + 7y + 3z = 44 To find a solution to a system of equations like this, we can use two steps. First we find the determinant of the coefficient matrix A, which in this case is: ⎛ 5 2 −9⎞ A = ⎜ −9 −3 2 ⎟ ⎜⎝ 6 7 3 ⎟⎠ CHAPTER 2 Vectors and Matrices 35 The determinant is: >> A = [5 2 –9; –9 –3 2; 6 7 3] >> det(A) ans = 368 When the determinant is nonzero, a solution exists. This solution is the column vector: ⎛ x⎞ x = ⎜ y⎟ ⎜⎝ z⎟⎠ MATLAB allows us to generate the solution readily using left division. First we create a column vector of the numbers on the right-hand side of the system. We find: >> b = [44;11;5]; >> A\b ans = –5.1250 7.6902 –6.0272 Finding the Rank of a Matrix The rank of a matrix is a measure of the number of linearly independent rows or columns in the matrix. If a vector is linearly independent of a set of other vectors that means it cannot be written as a linear combination of them. Simple example: ⎛ 1⎞ ⎛ 3⎞ ⎛ 5⎞ u = ⎜ ⎟ ,v = ⎜ ⎟ ,w = ⎜ ⎟ ⎝ −2⎠ ⎝ −4⎠ ⎝ −6⎠ Looking at these column vectors we see that: 2u + v = w 36 MATLAB Demystified Hence w is linearly dependent on u and v, since it can be written as a linear combination of them. On the other hand: ⎛ 2⎞ ⎛ 0⎞ ⎛ 0⎞ u = ⎜ 0⎟ , v = ⎜ −1⎟ , w = ⎜ 0⎟ ⎜⎝ 0⎟⎠ ⎜⎝ 0 ⎟⎠ ⎜⎝ 7⎟⎠ form a linearly independent set, since none of these vectors can be written as a linear combination of the other two. Consider the matrix: ⎛ 0 1 0 2⎞ A=⎜ ⎝ 0 2 0 4⎟⎠ The second row of the matrix is clearly twice the first row of the matrix. Hence there is only one unique row and the rank of the matrix is 1. Let’s check this in MATLAB. We compute the rank in the following way: >> A = [0 1 0 2; 0 2 0 4]; >> rank(A) ans = 1 Another example: ⎛ 1 2 3⎞ B = ⎜ 3 0 9⎟ ⎜⎝ −1 2 −3⎟⎠ The third column is three times the first column: 3 ⎛ 1⎞ 9 = 3⎜ 3 ⎟ −3 ⎜⎝ −1⎟⎠ CHAPTER 2 Vectors and Matrices 37 Therefore, it’s linearly dependent on the other two columns (add zero times the second column). The other two columns are linearly independent since there is no constant α such that: ⎛ 2⎞ ⎛ 1⎞ ⎜ 0⎟ = α ⎜ 3 ⎟ ⎜⎝ 2⎟⎠ ⎜⎝ −1⎟⎠ So we conclude that there are two linearly independent columns, and rank(B) = 2. Let’s check it in MATLAB: >> B = [1 2 3; 3 0 9; –1 2 –3]; >> rank(B) ans = 2 Now let’s consider the linear system of equations with m equations and n unknowns: Ax = b The augmented matrix is formed by concatenating the vector b onto the matrix A: [A b] The system has a solution if and only if rank(A) = rank(A b). If the rank is equal to n, then the system has a unique solution. If rank(A) = rank(A b) but the rank < n, there are an infinite number of solutions. If we denote the rank by r, then r of the unknown variables can be expressed as linear combinations of n – r of the other variables. Since the rank can be computed easily in MATLAB and we can readily concatenate arrays together, we can use these facts to analyze linear systems with relative ease. If the rank condition is met and the rank is equal to the number of unknowns, the solution can be computed by using left division. Let’s illustrate the technique. Consider the system: x − 2y + z = 12 3x + 4y + 5z = 20 −2x + y + 7z = 11 38 MATLAB Demystified The coefficient matrix is: ⎛ 1 −2 1⎞ A = ⎜ 3 4 5⎟ ⎜⎝ −2 1 7⎟⎠ We also have: ⎛12⎞ b = ⎜ 20⎟ ⎜⎝ 11⎟⎠ And the augmented matrix is: ⎛1 −2 1 12⎞ (A b) = ⎜ 3 4 5 20⎟ ⎜⎝ −2 1 7 11⎟⎠ The first step is to enter these matrices in MATLAB: >> A = [1 –2 1; 3 4 5; –2 1 7] b = [12; 20; 11] We can create the augmented matrix by using concatenation: >> C = [A b] C = 1 –2 1 12 3 4 5 20 –2 1 7 11 Now let’s check the rank of A: >> rank(A) ans = 3 The rank of the augmented matrix is: >> rank(C) ans = 3 CHAPTER 2 Vectors and Matrices 39 Since the ranks are the same, a solution exists. We also note that the rank r satisfies r = n since there are three unknown variables. This means the solution is unique. We find it by left division: >> x = A\b x = 4.3958 –2.2292 3.1458 Finding the Inverse of a Matrix and the Pseudoinverse The inverse of a matrix A is denoted by A−1 such that the following relationship is satisfied: AA−1 = A−1A = 1 Consider the following matrix equation: Ax = b If the inverse of A exists, then the solution can be readily written as: x = A−1b In practice, this is much harder than it looks because computing the inverse of a matrix can be a tedious pain. Luckily MATLAB makes things easy for us by doing all of the tedious work we want to avoid. The inverse of a matrix A can be calculated in MATLAB by writing: inv(A) The inverse of a matrix does not always exist. In fact, we can use the determinant to determine whether or not the inverse exists. If det(A) = 0, then the inverse does not exist and we say the matrix is singular. Let’s get started by calculating a few inverses just to see how easy this is to do in MATLAB. Starting with a simple 2 × 2 matrix: ⎛ 2 3⎞ A=⎜ ⎝ 4 5⎟⎠ 40 MATLAB Demystified First, let’s check the determinant: >> A = [2 3; 4 5] A = 2 3 4 5 >> det(A) ans = –2 Since det(A) ≠ 0, we can find the inverse. MATLAB tells us that it is: >> inv(A) ans = –2.5000 1.5000 2.0000 –1.0000 We can verify that this is the inverse by hand: ⎛ 2 3⎞ ⎛ −5 / 2 3 / 2⎞ ⎛ −10 / 2 + 6 6 / 2 − 3 ⎞ ⎛ 1 0⎞ AA−1 = ⎜ = = ⎝ 4 5⎟⎠ ⎜⎝ 2 −1 ⎟⎠ ⎜⎝ −20 / 2 + 10 12 / 2 − 5⎟⎠ ⎜⎝ 0 1⎟⎠ We aren’t going to bother to tell you how to calculate a matrix inverse by hand, that’s something you can find in most linear algebra books. Suffice it to say that it’s something you want to avoid doing, especially for larger matrices. Let’s consider a 4 × 4 case in MATLAB. First we create the matrix: >> S = [1 0 –1 2; 4 –2 –3 1; 0 2 –1 1; 0 0 9 8]; Checking its determinant we find: >> det(S) ans = –108 Since det(S) ≠ 0, the inverse must exist. MATLAB spits it out for us: >> T = inv(S) T = –0.9259 0.4815 0.4815 0.1111 –0.6296 0.1574 0.6574 0.0556 –0.5926 0.1481 0.1481 0.1111 0.6667 –0.1667 –0.1667 0 CHAPTER 2 Vectors and Matrices 41 Finding this by hand would not have been pleasant, and chances are we would have generated some errors. Now let’s check that this is in fact the inverse: >> S*T ans = 1.0000 0 0 0 0.0000 1.0000 –0.0000 0 0.0000 –0.0000 1.0000 0 0 0 0 1.0000 The –0.0000 terms come from some rounding errors and all that. Within computer precision, it looks like we do in fact have the correct inverse. Let’s check multiplication the other way: >> T*S ans = 1.0000 0 0 0 0 1.0000 0 0.0000 0 0 1.0000 0 0 0 0.0000 1.0000 This time, for mysterious reasons left behind the MATLAB curtain that aren’t important for those of us just using it for some basics, the result comes out a bit nicer. Now let’s look at how we can solve a system of equations using the inverse. Consider: 3x − 2y = 5 6x − 2y = 2 The coefficient matrix is: >> A = [3 –2; 6 –2] A = 3 –2 6 –2 The vector b for the system Ax = b is: >> b = [5;2] b = 5 2 42 MATLAB Demystified First let’s check the determinant of A to ensure that the inverse exists: >> det(A) ans = 6 Since the inverse exists, we can generate the solution readily in MATLAB: >> x = inv(A)*b x = –1.0000 –4.0000 We can only use the method described earlier, multiplying by the inverse of the coefficient matrix to obtain a solution, if the coefficient matrix is square. What this means for the system of equations is that the number of equations equals the number of unknowns. If there are fewer equations than unknowns, the system is called underdetermined. This means that the system has an infinite number of solutions. This is because only some of the unknown variables can be determined. The variables that remain unknown can assume any value, hence there are an infinite number of solutions. We take a simple example: x + 2y − z = 3 5y + z = 0 A little manipulation tells us that: z = − 5y x = 3 − 7y In this system, while we can find values for two of the variables (x and z), the third variable y is undetermined. We can choose any value of y we like, and the system will have a solution. Another case where an infinite number of solutions exist for a system of equations and unknowns is when det(A) = 0. So what is a poor mathematician to do in such a scenario? Luckily the pseudoinverse comes to the rescue. This solution gives the minimum norm solution for real values of the variables. That is, the solution vector x is chosen to have the smallest norm such that the components of x are real. Let’s consider a linear system of equations: 3x + 2y − z = 7 4y + z = 2 CHAPTER 2 Vectors and Matrices 43 Obviously this system has an infinite number of solutions. We enter the data: >> A= [3 2 –1; 0 4 1]; b = [7;2]; >> C = [A b] C = 3 2 –1 7 0 4 1 2 Now we compute the ranks: >> rank(A) ans = 2 >> rank(C) ans = 2 Since these ranks are equal, a solution exists. We can have MATLAB generate a solution using left division: >> x = A\b x = 2.0000 0.5000 0 MATLAB has generated a solution by setting one of the variables ( z in this case) to zero. This is typically what it does in cases like these, if you try to generate a solution using left division. The solution is valid of course, but remember it only holds when z = 0, and z can be anything. We can also solve the system using the pseudoinverse. We do this by typing: >> x = pinv(A)*b x = 1.6667 0.6667 –0.6667 MATLAB uses the Moore-Penrose pseudoinverse to calculate pinv. 44 MATLAB Demystified Reduced Echelon Matrices The MATLAB function rref(A) uses Gauss-Jordan elimination to generate the reduced row echelon form of a matrix A. A simple example you can verify with a hand calculation: >> A = [1 2; 4 7] A = 1 2 4 7 >> rref(A) ans = 1 0 0 1 Now let’s consider an example you’re unlikely to calculate by hand. A magic matrix is an n × n matrix. The components of the matrix range from 1 to n2 and the sum of the elements in a column is equal to the sum of the elements in a row. Trying to generate one of these by hand might cause a brain hemorrhage, but MATLAB does it for us with the magic(n) command. For example: >> A = magic(5) A = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 Let’s check the sum of the columns to see that they’re equal: >> sum(A) ans = 65 65 65 65 65 Using Gauss-Jordan elimination on this matrix to find the reduced row echelon form would be a bit too much work for me to tackle. So I am going to have MATLAB tell us what it is: >> rref(A) ans = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 CHAPTER 2 Vectors and Matrices 45 Well how about that. We got the identity again. Let’s try a larger matrix: >> magic(8) ans = 64 2 3 61 60 6 7 57 9 55 54 12 13 51 50 16 17 47 46 20 21 43 42 24 40 26 27 37 36 30 31 33 32 34 35 29 28 38 39 25 41 23 22 44 45 19 18 48 49 15 14 52 53 11 10 56 8 58 59 5 4 62 63 1 This matrix is too big for most of us to tackle, but MATLAB finds: >> rref(magic(8)) ans = 1 0 0 1 1 0 0 1 0 1 0 3 4 –3 –4 7 0 0 1 –3 –4 4 5 –7 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 Matrix Decompositions MATLAB can be used to quickly generate the LU, QR, or SVD decompositions of a matrix. In this section, we will take a look at LU decomposition and see how to use it to solve a linear system of equations in MATLAB. We can find the LU decomposition of a matrix A by writing: [L, U] = lu(A) For example, let’s find the LU decomposition of: ⎛ −1 2 0⎞ A = ⎜ 4 1 8⎟ ⎜⎝ 2 7 1⎟⎠ 46 MATLAB Demystified We enter the matrix and find: >> A = [–1 2 0; 4 1 8; 2 7 1]; >> [L, U] = lu(A) L = –0.2500 0.3462 1.0000 1.0000 0 0 0.5000 1.0000 0 U = 4.0000 1.0000 8.0000 0 6.5000 –3.0000 0 0 3.0385 We can use the LU decomposition to solve a linear system. Suppose that A was a coefficient matrix for a system with ⎛12⎞ b = ⎜ −8⎟ ⎜⎝ 6 ⎟⎠ The solution can be generated with two left divisions: x = U\(L\b) We find: >> x = U\(L\b) x = –6.9367 2.5316 2.1519 Consider the system: 3x + 2y − 9z = −65 −9x + 5y + 2z = 16 6x + 7y +3z = 5 We enter the system in MATLAB: >> A = [3 2 –9; –9 –5 2; 6 7 3]; b = [–65; 16; 5]; CHAPTER 2 Vectors and Matrices 47 Now let’s find the LU decomposition of A: >> [L, U] = lu(A) L = –0.3333 0.0909 1.0000 1.0000 0 0 –0.6667 1.0000 0 U = –9.0000 –5.0000 2.0000 0 3.6667 4.3333 0 0 –8.7273 Now we use these matrices together with left division to generate the solution: >> x = U\(L\b) x = 2.0000 –4.0000 7.0000 Quiz 1. Find the magnitude of the vector A = (−1 7 3 2). 2. Find the magnitude of the vector A = (−1 + i 7i 3 −2−2i). 3. Consider the numbers 1, 2, 3. Enter these as components of a column vector and as components of a row vector. 4. Given A = [1; 2; 3]; B = [4; 5; 6];, find the array product of the two vectors. 5. What command would create a 5 × 5 matrix with ones on the diagonal and zeros everywhere else? ⎛ 8 7 11⎞ ⎛ 2 1 2⎞ 6. Consider the two matrices A = ⎜ 6 5 −1 ⎟ , B = ⎜ −1 6 4⎟ and compute ⎜⎝ 0 2 −8⎟⎠ ⎜⎝ 2 2 2⎟⎠ their array product and matrix product. ⎛ 1 2 3⎞ ⎛ 7 8 9⎞ 7. Suppose that A = ⎜ 4 5 6 ⎟. Use it to create B = ⎜ 7 8 9⎟ ⎜⎝ 7 8 9⎟⎠ ⎜⎝ 4 5 6⎟⎠ 48 MATLAB Demystified 8. Find a solution to the following set of equations: x + 2y + 3z = 12 −4x + y + 2z = 13 9y − 8z = −1 What is the determinant of the coefficient matrix? 9. Does a solution to the following system exist? What is it? x − 2y + 3z = 1 x + 4y + 3z = 2 2x + 8y + z = 3 10. Use LU decomposition to find a solution to the system: x + 7y − 9z = 12 2x − y + 4z = 16 x + y − 7z = 16 CHAPTER 3 Plotting and Graphics Plotting is one of the most useful applications of a math package used on the computer, and MATLAB is no exception to this rule. Often we need to visualize functions that are too hard to graph “by hand” or to plot experimental or generated data. In this chapter we will introduce the commands and techniques used in MATLAB to accomplish these kinds of tasks. Basic 2D Plotting Let’s start with the most basic type of plot we can create, the graph of a function of one variable. Plotting a function in MATLAB involves the following three steps: 1. Define the function 2. Specify the range of values over which to plot the function 3. Call the MATLAB plot(x, y) function Copyright © 2007 by The McGraw-Hill Companies. Click here for terms of use. 50 MATLAB Demystified When specifying the range over which to plot the function, we must also tell MATLAB what increment we want it to use to evaluate the function. It doesn’t take a rocket scientist to figure out that using smaller increments will result in plots with a smoother appearance. If the increment is smaller, MATLAB will evaluate the function at more points. But it’s generally not necessary to go that small. Let’s look at a simple example to see how this works. Let’s plot the function y = cos(x) over the range 0 ≤ x ≤ 10. To start, we want to define this interval and tell MATLAB what increment to use. The interval is defined using square brackets [] that are filled in the following manner: [ start : interval : end ] For example, if we want to tell MATLAB to plot over 0 ≤ x ≤ 10 with an interval of 0.1, we type: [0:0.1:10] To assign this range to a variable name, we use the assignment operator. We also do this to tell MATLAB what the dependent variable is and what function we want to plot. Hence to plot y = cos(x), we enter the following commands: >> x = [0:0.1:10]; >> y = cos(x) Notice that we ended each line with semicolons. Remember, this suppresses MATLAB output. It’s unlikely you would want MATLAB to spit out all the x values over the interval onto the screen, so we use the semicolon to prevent this. Now we can plot the function. This is done by entering the following command: >> plot(x, y) After typing the plot command, hit the enter key. After a moment MATLAB will open a new window on the screen with the caption Figure 1. The plot is found in this window. For the example we used, we obtain the plot shown in Figure 3-1. Now what about the increment? Suppose that we make the increment ten times as large, so we set it to 1. This is done by entering the following command: >> x = [0:1:10]; If we try to plot again, we get an error message: >> plot(x, y); ??? Error using ==> plot Vector must be the same lengths. CHAPTER 3 Plotting and Graphics 51 Figure 3-1 A plot of y = cos(x) generated by MATLAB for 0 ≤ x ≤ 10 We had already made the definition y = cos(x), yet MATLAB can’t plot it. What happened here? Turns out we need to tell MATLAB to reevaluate the function for the number of points and values that we gave it when we redefined x. In other words, the correct course of action is to reenter all of the commands all over again: >> y = cos(x) y = Columns 1 through 10 1.000 0.5403 -0.4161 -0.9900 -0.6536 0.2837 0.9602 0.7539 -0.1455 -0.9111 Column 11 -08391 >> plot(x, y) A quick aside—notice that we left off the semicolon after our definition of y—so MATLAB outputs the evaluation of cos(x) at each point. If you have a large number of points, you can see that this probably would be undesirable. OK back to the plot. When we plot with a larger increment, the plot is less accurate. Look at what MATLAB generates for y = cos(x) in Figure 3-2, where we used an increment size of 1. The plot of the function in this case is choppy. Let’s try going the other way. We will make the increment ten times smaller than our original attempt, setting it to 0.01. 52 MATLAB Demystified Figure 3-2 A plot of the cosine function with a larger increment Remember we need to redefine y again, therefore the commands we need to type in are: >> x = [0:0.01:10]; >> y = cos(x); >> plot(x, y) This time we get a very nice smooth rendition of y = cos(x), this is shown in Figure 3-3. OK now we know how to get a straightforward plot on the screen. The next thing you might want to do is generate a plot that had the axes labeled. This can be done using the xlabel and ylabel functions. These functions can be used with a single argument, the label you want to use for each axis enclosed in quotes. Place the xlabel and ylabel functions separated by commas on the same line as your plot command. For example, the following text generates the plot shown in Figure 3-4: x=[0:0.01:10]; y=cos(x); plot(x,y), xlabel(‘x’), ylabel(‘cos(x)’); CHAPTER 3 Plotting and Graphics 53 Figure 3-3 A plot of y = cos(x) with a smaller increment Figure 3-4 Sprucing up the plot with axis labels 54 MATLAB Demystified More 2D Plotting Options OK so at this point we basically know how to spit out a generic plot of a given function. Let’s look at some other options we might consider with plots. If you’re going to use a plot in a presentation or homework assignment, you might want to give the plot a title. MATLAB allows you to do this by using the title command which takes a character string enclosed in single quotes. The title is printed just above the plot. Let’s say that we were plotting some force data that happened to vary as f(t) e−2t sin t for 0 ≤ t ≤ 4, where t is time in seconds with data at intervals of 0.02 seconds. We want to title the plot “Damped Spring Forcing.” How do we do it? The first step is to define our interval. We do this in the usual way, calling our independent variable t instead of x. >> t = [0:0.02:1]; Now let’s define our function. This should be pretty straightforward: >> f = exp(-t)*sin(t); However, if you try this, you’ll notice we get an error message. MATLAB tells us that ??? Error using ==> mtimes Inner matrix dimensions must agree. So how do we get around this? One way is to use the fplot function instead. The function fplot gets around our choice of interval used to generate the plot, and instead decides the number of plotting points to use for us. Generally, fplot will allow you to generate the most accurate plots possible, but it also helps us get around errors like these. The formal call to fplot goes like fplot ( ‘function string,’ [xstart, xend]). The argument function string tells fplot the function you want to plot while xstart and xend define the range over which to display the plot. This is pretty straightforward, let’s see how it works out in the current example. We can do it all in one go by typing the following command and hitting the enter key: >> fplot('exp(-2*t)*sin(t)',[0, 4]; MATLAB quickly produces the plot shown in Figure 3-5. If we want to add labels and a title to the plot, we can follow the same procedure used with plot(x,y). Let’s try it again this time adding our title “Damped Spring Forcing” and labeling our axes: fplot('exp(–2*t)*sin(t)',[0,4]), xlabel('t'), ylabel('f(t)'), title('Damped Spring Forcing') CHAPTER 3 Plotting and Graphics 55 Figure 3-5 The function f(t) e−2t sin t generated using the fplot command This produces the labeled plot shown in Figure 3-6. Well this provided a nice intro to the fplot command, but it turns out we had a typo in our command multiplying the exponential and trig function which generated the error. We had typed: >> f = exp(-t)*sin(t); ??? Error using ==> mtimes Inner matrix dimensions must agree. The correct way to type this in MATLAB is to include a period prior to the multiplication symbol. Confused? Let’s show the correct way to type this function. >> t = [0:0.01:4]; >> f = exp(-2*t).*sin(t); >> plot(t, f) This time, there is no error and the function plots correctly. Therefore, when generating a function, which is formed by the product of two or more other functions, be sure to tell MATLAB we’re multiplying two matrices by including a ‘.’ character. 56 MATLAB Demystified Figure 3-6 A labeled plot generated with the fplot command For the current example we replaced >> f = exp(-t)*sin(t); with y = exp(-1.2*x).*sin(10*x + 5);. The difference is that in the second case, we used matrix multiplication (indicated by typing.*). Well we are back to the old plot(x, y) command. What are some other ways we can spruce up your basic two-dimensional plot? One way is to add a grid to the plot. This is done by adding the phrase grid on to your plot statement. For the next example, we will plot y = tanh(x) over the range −6 ≤ x ≤ 6 with a grid display. First we define our interval: >> x = [–6:0.01:6]; Next, we define the function: >> y = tanh(x); The plot command looks like this, and produces the plot shown in Figure 3-7. Plot(x,y),grid on CHAPTER 3 Plotting and Graphics 57 Figure 3-7 A plot made with the grid on command The Axis Commands MATLAB allows you to adjust the axes used in two-dimensional plots in the following way. If we add axis square to the line containing the plot command, this will cause MATLAB to generate a square plot. If we type axis equal, then MATLAB will generate a plot that has the same scale factors and tick spacing on both axes. Let’s return to the example y = tanh(x), which we plotted in Figure 3-7. If you run this plot with axis square, you will get the same plot that we did using the default settings. But suppose that we typed: >> plot(x,y),grid on, axis equal In this case, we get the plot shown in Figure 3-8. Notice that the spacing used for the y axis in Figure 3-7 and Figure 3-8 are quite different. In the first case, the spacing used on the vertical or y axis is different than the spacing used on the x axis. In contrast, in Figure 3-8, the spacing is identical. 58 MATLAB Demystified Figure 3-8 Plotting y = tanh(x) using the axis equal option As you can see from this dramatic example, we can use the axis command to generate plots that differ quite a bit in appearance. Hence we can use the command to play with different plot styles and select what we need for the particular application. To let MATLAB set the axis limits automatically, type axis auto. This isn’t necessary, of course, unless you’ve been playing with the options described here. Showing Multiple Functions on One Plot In many cases, it is necessary to plot more than one curve on a single graph. The procedure used to do this in MATLAB is fairly straightforward. Let’s start by showing two functions on the same graph. In this case let’s plot the following two functions over 0 ≤ t ≤ 5: f(t) = e−t g(t) = e−2t CHAPTER 3 Plotting and Graphics 59 We will differentiate between the two curves by plotting g with a dashed line. Following the usual procedure, we first define our interval: >> t = [0:0.01:5]; Next, we define the two functions: >> f = exp(–t); >> g = exp(–2*t); To plot multiple functions, we simply call the plot(x, y) command with multiple pairs x, y defining the independent and dependent variables used in the plot in pairs. This is followed by a character string enclosed in single quotes to tell us what kind of line to use to generate the second curve. In this case we have: >> plot(t,f,t,g,'--') This tells MATLAB to generate plots of f(t) and g(t) with the latter function displayed as a dashed line. Note that while we can’t show it in the book, MATLAB displays each curve with a unique color. The result is shown in Figure 3-9. MATLAB has four basic line types that can be defined in a plot. These are, along with the character strings, used to define them in the plot command: Solid line ′-′ Dashed line ′--′ Figure 3-9 Plotting two curves on the same graph 60 MATLAB Demystified Figure 3-10 Using a dotted line to represent f(t) = e−t and a dashed line to represent g(t) = e−2t Dash-dot line ′-.′ Dotted line ′:′ Let’s generate the same graph as in Figure 3-9 making the curve f(t) = e−t appear with a dotted line. The command is plot(t,f,':',t,g,'--') This generates the plot shown in Figure 3-10. If you want to plot all curves using solid lines and simply differentiate them by their colors, just leave off the character string specifying the curve type. The plot will be generated using solid lines, which is the default. Adding Legends A professionally done plot often has a legend that lets the reader know which curve is which. In the next example, let’s suppose that we are going to plot two potential energy functions that are defined in terms of the hyperbolic trig functions sinh(x) and cosh(x) for 0 ≤ x ≤ 2. First we define x: >> x = [0:0.01:2]; CHAPTER 3 Plotting and Graphics 61 Now we define our two functions. There is nothing magical about calling a function y or anything else in MATLAB, so let’s call the second function z. So we have >> y = sinh(x); >> z = cosh(x); The legend command is simple to use. Just add it to the line used for the plot(x, y) command and add a text string enclosed in single quotes for each curve you want to label. In our case we have: legend('sinh(x)','cosh(x)') We just add this to the plot command. For this example, we include x and y labels as well, and plot the curves using a solid line for the first curve and a dot-dash for the second curve: >> plot(x,y,x,z,'-.'),xlabel('x'),ylabel('Potential'),legend('sinh(x)','cosh(x)') The plot that results is shown in Figure 3-11. The legend didn’t originally show up where it is in the figure, and it probably won’t do so on your system either. To move the legend to a more favorable position that might be better for printing or display, just hold the mouse pointer over the legend and drag it to the location where you want it to display. Figure 3-11 A plot of two curves that includes a legend 62 MATLAB Demystified Setting Colors The color of each curve can be set automatically by MATLAB or we can manually select which color we want. This is done by enclosing the appropriate letter assigned to each color used by MATLAB in single quotes immediately after the function to be plotted is specified. Let’s illustrate with an example. Let’s plot the hyperbolic sine and cosine functions again. This time we’ll use a different interval for our plot, we will take −5 ≤ x ≤ 5. So we define our data array as >> x = [–5:0.01:5]; Now we redefine the functions. Remember if we don’t do this and we’re in the same session of MATLAB, the program is going to think that the functions are defined in terms of the previous x we had used. So now we type: >> y = sinh(x); >> z = cosh(x); Now we will generate the plot representing y with a red curve and z with a blue curve. We do this by following our entries for y and z in the plot function by the character strings ′r′ and ′b′ respectively. The command looks like this: >> plot(x,y,'r',x,z,'b') Try this on your own system to see the plot it generates. Now, it is possible to set