GETTING STARTED WITH MATLAB-RUDRAPRATAP - Free ebook download as PDF File .pdf), Text File .txt) or read book online for free. MATLAB. 7. Actual examples: Actual examples carried out in MATLAB are shown in gray, shaded. medical-site.info - Download as Visit This Again. .. Rudra Pratap. and test-learning of many people. Rudra Pratap is the author of Getting Started with MATLAB 7 ( avg rating, ratings, 5 reviews, published ), Getting Started with MATLAB (
|Language:||English, Spanish, Japanese|
|Genre:||Children & Youth|
|Distribution:||Free* [*Register to download]|
Enhanced by fun and appealing illustrations, Getting Started with MATLAB: A Quick Introduction for Scientists and Engineers, Seventh Edition, employs a casual. The document is written as a PDF, with internal links as well as links to online .. 1 Getting Started with the MATLAB Environment. 7 Fibonacci Numbers. MATLAB: A Quick Introduction for Scientists and Engineers (Rudra Pratap, ). 7. Built-in functions. Plotting. 3. Programming in MATLAB. M- files To start the program on a UNIX machine, just type matlab at the prompt of a command shell. You will then . The error messages that we get from MATLAB can be quite informative Rudra Pratap, Saunders College Publishing,
Array operations are known to cause irritability and minor itching to beginners. The author, however, might download the reader a cup of coffee in the case of serious distress.
In rare cases of very flattering comments or very creative suggestions about improving this book, the author might even download the reader lunch. Bachcha Singh Contents Preface 1 1 Introduction 3 1. Working with Arrays of Numbers. Creating and Printing Simple Plots. Creating, Saving, and Executing a Script File. Creating and Executing a Function File. Working with Files and Directories.
Finding the determinant of a matrix. Finding eigenvalues and eigenvectors. Scripts and Functions 85 4. A second-order nonlinear ODE. Now, I expect and enjoy interactive calculation, programming, graphics, animation, and complete portability across platforms—all under one roof.
It is not a complete miracle drug, but I like it and I think you will probably like it too. Although the graphics capability was limited to bare-bones 2-D plots, and programming was not possible on the mainframe VAX, I still loved it. I did all the computations for my Ph. I have given several introductory lectures, demonstrations, and hands-on workshops.
This book is a result of my involvement with MATLAB teaching, both informal and in the class room, over the last several years. This book is intended to get you started quickly.
After an hour or two of getting started you can use the book as a reference. There are many examples, which you can modify for your own use. This update re- quired checking each command and function given in this book as examples, and changing them if required. New versions of software packages usually add fea- tures that their experienced users ask for.
As a result, the packages and their 2 Preface manuals get bigger and bigger, and more intimidating to a new user. I have tried hard to protect the interests of a new user in this book. It has been a struggle to keep this book lean and thin, friendly to beginners, and yet add more features and applications. In response to emails I have received from several readers across the globe, I have added more exercises in this edition.
I have also added substantial material in Chapter 3 Interactive Computation and Chapter 5 Applications. I was helped through the development of this book by the encouragement, criticism, editing, typing, and test-learning of many people, especially at Cornell University and the Indian Institute of Science.
I thank all students who have used this book in its past forms and provided constructive criticism. I greatly appreciate your words of encouragement. Hall, James R. Wohlever, John T. Cipolla, John C. In addition, I must acknowledge the help of three special people. Andy Ruina has been an integral part of the development of this book all along. In fact, he has written most of Chapter 8, the introduction to the Symbolic Math Toolbox.
My ed- itor Peter Gordon at Oxford University Press has always been supportive and kept his word on keeping the price of the book low. Lastly, I thank my wife, Kalpana, for being incredibly supportive through- out. Despite their arrival, if this edition of the book is in your hands, it is because of my wife who provided me with the time to work on the book by shouldering more than her fair share of family responsibilities.
Thank you all. Bangalore Rudra Pratap. May, Introduction 1. It provides an interactive environment with hundreds of built-in functions for technical computation, graphics, and animation.
Best of all, it also provides easy extensibility with its own high-level pro- gramming language. The diagram in Fig. Most of these functions use state-of- the art algorithms. There are numerous functions for 2-D and 3-D graphics as well as for animation. Once written, these functions behave just like the built-in functions.
The fundamental data-type is the array. Vectors, scalars, real matrices and complex matrices are all automatically handled as special cases of the basic data-type. What is more, you almost never have to declare the dimensions of a matrix. Consequently, vectorized 1. See Section 8. Mathematica, Maple, and Macsyma are primarily symbolic algebra packages. Of course, they do numerical computations too. In fact, if you know any of these packages really well, you can do almost every calcu- lation that MATLAB does using that software.
There are other packages, such as Xmath, that are also closer in aim and scope but seem to be popular with people in some specialized application areas. The bottom line is, in numerical computations, especially those that utilize vectors and matrices, MATLAB beats everyone hands down in terms of ease of use, availability of built-in functions, ease of programming, and speed.
There are more than universities and thousands of companies listed as registered users. Software packages that do symbolic algebra are also known as Computer Algebra Systems. Contact the com- pany for product information and ordering at the following address: The MathWorks Inc.
The goal is to get started as simply as possible. It takes a while to understand its real power. Unfortunately, most powerful packages tend to be somewhat intimidating to a beginner. That is why this book exists — to help you overcome the fear, get started quickly, and become productive in very little time. All features are discussed through examples using the following conventions: So, a command shown as help topic implies that you have to type the actual name of a topic in place of topic in the command.
Explanatory notes have been added within small white rectangles in the gray boxes as shown below. The texts in the white boxes inside these gray boxes are explanatory notes.
Most of the ex- amples are designed so that you can more or less follow them without reading the entire text. All examples are system-independent. After trying out the examples, you should read the appropriate sections.
We encourage the use of on-line help. For almost all major topics, we indicate the on-line help category in a small box in the margin as shown here.
For on-line help type: Detailed help can then be obtained for any of those commands and functions. We discourage a passive reading of this book. The best way to learn any computer software is to try it out. We believe this, practice it, and encourage you to practice it too. So, if you are impatient, quickly read Sections 1. Command window: This is the main window.
If you can get to the command window, we advise you to ignore the other four subwindows at this point. As software packages, such as MATLAB, become more and more powerful, their creators add more and more features to address the needs of experienced users. Unfor- tunately, it makes life harder for the beginners — there is more room for confusion, distraction, and intimidation. Although, we describe the other subwindows here that appear with the command window, we do not expect it to be useful to you till you get to Lesson 6 in Chapter 2.
Launch Pad: You can launch any of the listed applications by double clicking on them. This subwindow lists all variables that you have gen- erated so far and shows their type and size. You can do various things with these variables, such as plotting, by clicking on a vari- able and then using the right button on the mouse to select your option.
Command History: All commands typed on the MATLAB prompt in the command window get recorded, even across multiple ses- sions you worked on Monday, then on Thursday, and then on next Wednesday, and so on , in this window. You can select a command from this window with the mouse and execute it in the command window by double clicking on it. Current Directory: You also have 1. Graphics window: Edit window: You can use any text editor to carry out these tasks.
For example, on Unix systems, typing!
The com- mands lookfor, help, helpwin, and helpdesk provide on-line help. See Section 3. The program includes a tutorial introduction that is worth trying. The following features hold for all forms of input-output: The Figure and the Editor windows appear only when invoked with the appropriate commands. For example, there is no need to declare variables as real or complex. No dimen- sion statements are required for vectors or arrays. However, we do not recommend it.
A semicolon at the end of a command suppresses the screen output, except for graphics and on-line help commands. The following facilities are provided for con- trolling the screen output: See Section 4. We do not discuss this facility in this book.
The default is format short. The display format is set by typing format type on the command line see Fig. This helps in editing previous commands. Almost all commands work the same way.
The user interface how you interact with your computer , however, may vary a little from platform to platform. On PCs: On Unix machines: Type matlab on the Unix prompt and hit re- turn. If it is not, ask your system administrator. If not, you have to create a separate folder for saving your work. We recommend the latter. Although, many of these things would probably not make sense to you right now, they are here, and you can come back to them whenever they seem relevant.
Not being in the right directory: Use cd or path; cd is easier to use but applies only to the current session. With path command, you can save the path to your directory and have MATLAB automatically access your directory every time you use it.
Use the on-line help to see how to set the path. Also, see Lesson-6 in the tutorials Chapter 2. This can happen due to various reasons.
There are various other little things that cause trouble from time to time. We point them out throughout the book wherever they raise their head. Each lesson should take about 10—15 minutes. We urge you also to do the exercises given at the end of each lesson.
This will take more time, but it will teach you quite a few things. If you get stuck in the exercises, simply turn the page; answers are on the back. Most answers consist of correct commands to do the exercises. But there are several correct ways of doing the problems. Before You Start You need some information about the computer you are going to work on. If you are working on your own computer, you will most likely know the answer to these questions. If you are working on a computer in a public facility, the system manager can help you.
In public facilities, sometimes the best thing to do is to spot a friendly person working there and ask these questions politely. People are usually nice! Here are the lessons in a nutshell: Key features: Learn to add, multiply, and exponentiate numbers, use trig functions, and control screen output with format. Create and work with arrays, vectors in particular. Learn to create, add, and multiply vectors, use sin and sqrt functions with vector arguments, and use linspace to create a vector.
Plot simple graphs. Learn to plot, label, and print out a circle. Time Estimates: The arithmetic operators are: Some commands and their output are shown below. Go ahead and reproduce the results. You can also assign the value of an expression to a variable. A semicolon at the end suppresses screen output.
You can recall the value of y by simply typing y. Here is arccosine of The floating point output display is controlled by the format command. Here are two examples. More info on this later. You can also quit by selecting quit from the file menu on Macs and PCs. Arithmetic operations: Compute the following quantities: Exponential and logarithms: The mathematical quantities e x , lnx, and log x are calculated with exp x , log x , and log10 x , respec- tively.
Calculate the following quantities: You can verify the result by direct substitution. The inverses, e. The same is true for hyperbolic functions. The inverse function atan2 takes 2 arguments, y and x, and gives the four-quadrant inverse tangent.
The argument of these functions must be in radians. Complex numbers: The former case is always interpreted as a complex number whereas the latter case is taken as complex only if i has not been assigned any local value. The same is true for j. Compute the following quantities. Can you check the result by hand calculation? Command Result exp 3 Working with Arrays of Numbers 25 2. Creating and Working with Arrays of Numbers Goal: To learn how to create arrays and vectors, and how to perform arithmetic and trigonometric operations on them.
An array is a list of numbers or expressions arranged in horizontal rows and vertical columns. When an array has only one row or column, it is called a vector. This lesson deals primarily with one-dimensional arrays, i. One of the exercises introduces you to two-dimensional arrays, i. There are many mathematical concepts associated with vectors and matrices that we do not mention here. So go ahead and try the commands shown on the next page.
Once again, you are going to reproduce the results shown. But you cannot add or subtract a row vector to a column vector. You can add or subtract two vectors of the same size. Create a vector x with 5 elements linearly spaced between 0 and Trigonometric functions sin, cos, etc. Figure 2. Some simple calculations with vectors.
Equation of a straight line: Your command should not involve any array operators since your cal- culation involves multiplication of a vector with a scalar m and then addition of another scalar c. Multiply, divide, and exponentiate vectors: Create a vector t with 10 elements: Now compute the following quantities: Points on a circle: Of course, you could compute x 2 by x. The geometric series: This is funky!
You know how to compute x n element-by-element for a vector x and a scalar exponent n. How about com- puting n x , and what does it mean? The result is again a vector with elements n x1 , n x2 , n x3 etc. Create a vector n of 11 elements from 0 to Repeat the procedure taking n from 0 to 50 and then from 0 to Matrices and vectors: Go to Fig.
Now create a vector and a matrix with the following commands: Find the sizes of v and M using the size com- mand. The last command M: Creating and Printing Simple Plots 29 2. Creating and Printing Simple Plots Goal: The MATLAB commands used are plot creates a 2-D line plot axis changes the aspect ratio of x and y axes xlabel annotates the x-axis ylabel annotates the y-axis title puts a title on the plot, and print prints a hardcopy of the plot. This lesson teaches you the most basic graphics commands.
The exercises take you through various types of plots, overlay plots, and more involved graphics. You are going to draw a circle of unit radius. For generating data, use the parametric equation of a unit circle: In the sample session shown here, only the commands are shown. You should see the output on your screen.
Calculate x and y coordinates. Plot x vs. Label the x-axis with x. Label the y-axis with y. Put a title on the plot. Print on the default printer. Plotting and printing a simple graph. Text strings are entered within single right-quote. For more information on text strings, see Section 3. A simple sine plot: Make the same plot as above, but rather than displaying the graph as a curve, show the unconnected data points.
You may peep into Section 6. An exponentially decaying sine plot: You need array multiplication between exp Space curve: On-line help: This should give you paged screen output. Read through the on-line help. To move to the next page of the screen output, simply press the spacebar.
Log scale plots: The plot commands semilogx, semilogy, and loglog, plot the x-values, the y-values, and both x- and y-values on a log 10 scale, respectively. Overlay plots: You might like to read Section 6. Fancy plots: Go to Section 6. Reproduce any of the plots you like. Use your knowledge of splines and interpolation to draw a lizard just kidding.
You should not be looking for answer here. If the last command legend does produce a legend on your plot, click and hold your mouse on the legend and see if you can move it to a location of your liking.
See page for more information on legend. Creating, Saving, and Executing a Script File 33 2. For more information, see Section 4. The commands needed to accomplish these tasks depends on the operating system and the text editor you use. It is not possible to provide an introduction to these topics here. You are essentially going to write the commands shown in Fig. Follow the directions below. Select New M-File from the File menu. A new edit window should appear.
Select Save As A dialog box should appear. Type the name of the document as circle. Execute the file. You should see the circle plot in the Figure Window. Show the center of the circle: See Exercises 2 and 7 of Lesson 3. Change the radius of the circle: When asked, enter a value for the radius and press return. Variables in the workspace: You can get information about them and access them, too: You should see the variables r, theta, x and y in the list.
All three variables are row vectors. Typing a single right quote. The contents are displayed by the type command. To see the contents of circle.
H1 line: It is this line that is searched by the lookfor command. Just for fun: See the on-line help on these commands before using them.
Do not worry, just copy it if you like it. See the on-line help on the commands used, e. Creating and Executing a Function File 37 2. Creating and Executing a Function File Goal: We advise you to select the latter option.
Select Open M-File from the File menu. Type the name of the document as circlefn. Try it out. You can also specify the value of the input directly. To understand how it works see Section 3.
Type help function to get on-line help on function. Convert temperature: Write a function that outputs a conversion-table for Celsius and Fahrenheit temperatures.
The input of the function should be two numbers: T i and T f , specifying the lower and upper range of the table in Celsius.
The output should be a two column matrix: Note that your output will be named temp. Calculate factorials: Write a function factorial to compute the factorial n! The input should be the number n and the output should be n!. You might have to use a for loop or a while loop to do the calculation. You can use the built-in function prod to calculate factorials.
For example, n! In this exercise, however, do not use this function. Compute the cross product: Check your function by taking cross products of pairs of unit vectors: Do not use the built-in function cross here. Sum a geometric series: Thus the input to the function must be r and n and the output must be the sum of the series. Calculate the interest on your money: For screen output, use format bank. If so, look them up or ignore them. This cross product is beyond me.
Creating and Executing a Function File 41 5. Working with Files and Directories Goal: You will explore some of these features now. In addition, you will also learn commands that pretty much do the same thing from the command line.
The commands that you will use are pwd, dir, ls, cd, what, and path. Let us go step by step. Where are you? This information is available in three ways: Look at the command window toolbar. There is a small win- dow that shows the name of the current directory along with its path. For example, Fig. As the path indicates, it is inside the matlabR12 directory. Which directory are you in?
Working with Files and Directories 43 2. You can get the same information from the command line by typ- ing pwd print working directory. The current directory is also displayed in a separate subwindow to the left of the command window.
If it is not visible, click on the Current Directory tab. This subwindow also lists the contents of the current directory.
How do you change the current directory? You can change the cur- rent directory with the cd DirectoryName command on the command line or by navigating through the browse button the button with three dots on it located next to the current directory peep-in window.
What are the contents of the current directory? You can see the con- tents of the current directory in the Current Directory subwindow Fig.
You can create a directory 44 Tutorial Lessons Figure 2. What are those other windows? On the left of the Command Window, there are four other subwindows, usually two visible and two hidden behind see Section 1. In particular, do the following. Click on the tab for this subwin- dow if it is not already in the foreground. Type the following commands in the command window. Click on the tab for this subwindow if it is not already in the foreground.
You can change any values in the array here. Select any option from the pop-up menu. You can edit, import, graph, or save the variable with a click of the mouse. The basic things to keep in mind are: Where to type commands: How to execute commands: To execute a command or statement, you must press return or enter at the end.
What to do if the command is very long: You can keep continuing this way till the length of your command hits the limit, which is characters. For more information see the discussion on Continuation on pages 49 and How to name variables: Names of variables must begin with a letter. What is the precision of computation: All computations are carried out internally in double precision. The appearance of numbers on the screen, however, depends on the format in use see Section 1.
The default is format short, which displays four digits after the decimal. For other available for- mats and how to change them, see Section 1. How to suppress the screen output: A semicolon ; at the end of a command suppresses the screen output, although the command is car- ried out and the result is saved in the variable assigned to the command or in the default variable ans. How to set paged-screen display: For paged-screen display one screen- ful of output display at a time use the command more on.
Where and how to save results: How to print your work: The simplest way, perhaps, is to create a diary with the diary command see Section 3. Before you print, make sure that the command window is the active window. What about comments: You are not likely to use a lot of comments while computing interactively, but you will use them when you write programs in MATLAB.
Since MATLAB derives most of its power from matrix computations and assumes every variable to be, at least potentially, a matrix, we start with descriptions and examples of how to enter, index, manipulate, and perform some useful calculations with matrices. The entire matrix must be enclosed within square brackets. It is entered the same way as a matrix. See Fig. Continuation If it is not possible to type the entire input on the same line then use three consecutive periods The three periods are called an ellipsis.
A matrix can also be entered across multiple lines using carriage returns at the end of each row. In this case, the semicolons and ellipses at the end of each row may be omitted. Thus, the following three commands are equivalent: This construct may be used for other commands and for a long list of command arguments see Section 4. This notation is fairly common in computational software packages and programming languages. For example, the statement A m: Thus A: When a matrix is entered by spec- ifying a single element or a few elements of the matrix, MATLAB creates a matrix just big enough to accommodate the elements.
Rows are separated by semicolons and columns are separated by spaces or commas. Element A ij of Matrix A is accessed as A i,j. Correcting any entry is easy through indexing. Any submatrix of A is obtained by using range specifiers for row and column indices. The colon by itself as a row or column index specifies all rows or columns of the matrix. A row or a column of a matrix is deleted by setting it to a null vector [ ].
Figure 3. Examples of matrix input and matrix index manipulation. By specifying vectors as the row and column indices of a matrix one can reference and modify any submatrix of a matrix. In such manipulations, it is imperative, of course, that the sizes of the submatrices to be manipulated are compatible.
Then Q v,: The vector is produced by logical or relational operations see Sec- tions 3. The vector created by you is converted into a logical array with the command logical. For example, to get the 1st, 4th, and 5th rows of Q with vectors, you can do: As a vector: Now let us look at some frequently used manipulations. However, it is advis- able in the following two cases. Large matrices: If you are going to generate or manipulate a large matrix, initialize the matrix to a zero matrix of the required dimension.
Dynamic matrices: If the rows or columns of a matrix are computed in a loop e. Once created, a row or column of any size may be appended to A as described below. Appending a row or column A row can be easily appended to an existing matrix provided the row has the same length as the length of the rows of the existing matrix. The same thing goes for columns. A row or column of any size may be appended to a null matrix. Deleting a row or column Any row s or column s of a matrix can be deleted by setting the row or column to a null vector.
Utility matrices For on-line help type: A matrix can be built with many block matrices as well. See examples in Fig. Here is a list of some more functions used in matrix manipulation: Special matrices For on-line help type: For a complete list and help on these matrices, type help specmat.
Create a matrix D by putting d on the main diagonal, d1 on the first upper diagonal and d2 on the second lower diagonal. Create vectors d,d1, and d2 of length 4, 3, and 2 respectively. The commands zeros, ones, and rand work in a similar way. This command pulls out the diagonal of B in a row vector. Without the transpose, the result would obviously be a column vector. The second argument of the command specifies the off-diagonal vector to be pulled out. Here we get the first upper off-diagonal vector.
A negative value of the argument specifies the lower off-diagonal vectors. Examples of matrix manipulation using utility matrices and functions.
Finally, we mention the use of two frequently used built-in functions to generate vectors: Thus logspace a,b,n is the same as The array operation. The left division: This division is used to solve a matrix equation. Array operation: You can do array operation — operations done on element-by-element basis.
Element-by- For on-line help type: The same is true for matrices. Once 3. While u. These operations result in a vector or matrix of the same size as the operands, with 1 where the relation is true and 0 where it is false. Two or more of these operations can also be combined with the help of logical operators described below. Here x is the transpose of the first row of A. Matrix or vector products are well- defined between compatible pairs.
Look how easy it is to multiply a vector with a matrix-- compare with Fortran or Pascal. You can even exponentiate a matrix if it is a square matrix. So, A. Examples of matrix transpose, matrix multiplication, matrix exponentiation, and array exponentiation.
Since the output of the logical operations is a vector or a matrix, the output can be used as the index of a matrix to extract appropriate elements. In addition to these logical operators, there are many useful built-in logical functions, such as: To complete this list of logical functions, we just mention isreal, issparse, isstr, and isglobal.
Thus, they produce an output matrix of the same size as the input matrix. Trigonometric functions sin Sine. The angles given to these functions as arguments must be in radians. All of these functions, except atan2, take a single scalar, vector, or matrix as in- put argument. The function atan2 takes two input arguments: This gives the angle in a rectangular to polar conversion.
Exponential functions exp Exponential. So how do you compute e A? See the next section. Clearly, these are array operations. See the next section Section 3. Complex functions abs Absolute value. There are some built-in functions that are truly matrix functions, and that also have array counterparts. The matrix functions are: The array counterparts of these functions are exp, log, and sqrt, which operate on each element of the input matrix see Fig. The matrix exponential function expm also has some specialized variants expm1, expm2, and expm3.
See the on-line help or the Reference Guide  for their proper usage. Therefore, to create a column vector of text objects, each text string must have exactly the same number of characters. It gives the square root of each element of A as is evident from the output here. Similarly, exp gives element-by- element exponential of the matrix, whereas expm finds the true matrix exponential e A. For info on other matrix functions, type help matfun. An easier way of doing the same thing is to use the command char, which converts strings to a matrix.
Since the same quote character the single right quote is used to signal the beginning as well as the end of a string, this character cannot be used inside a string for a quote or apostrophe. Manipulating character strings Character strings can be manipulated just like matrices. This feature can be used along with number-to-string conversion functions, such as num2str and int2str, to create text objects containing dynamic values of variables. There are several built-in functions for character string manipulation: The functions char and strvcat seem to do the same thing — create string arrays by putting each argument string in a row.
So, what is the dif- ference? Try the com- mands: There are many uses of the eval function. For example, you can use eval to run a set of commands ten times while you take a two-hour lunch break.
So read them carefully. Note that while save and x, y, z are enclosed within quotes to make them character strings, the variable outputfile is not enclosed within quotes because it is already a string. The brackets are not a part of the eval command. These spaces are essential. Can you see why? Try to produce the string with and without the spaces. See page 93 for a discussion on feval. However, there is a quicker way of programming functions if they are not too complicated.
The syntax for creating an inline-function is particularly simple: We can modify it easily by changing the arithmetic operator to accept array argument: Once the function is created, you can use it as a function independently e. There are several examples of these functions in Section 3. Modify F x so that x can be an array i. Evaluate F x when x is a vector. You can also use F x as an input argument of another function. You can also use F x as input argument to those functions that require user defined function.
Here we use fzero to find a zero of F x. See on-line help on fzero.
Create another inline function F x,y of two variables. Check its symmetry by evaluating F x,y at 1,2 and 2,1. Bachcha Singh. Contents Preface 1 1 Introduction 3 1. Working with Arrays of Numbers. Creating and Printing Simple Plots. Creating, Saving, and Executing a Script File. Creating and Executing a Function File. Working with Files and Directories. Finding the determinant of a matrix. Finding eigenvalues and eigenvectors. Scripts and Functions 85 4. You've reached the end of this preview.