MATLAB, a software package for high-performance numerical computation and visualization, is one of the most widely used tools in the engineering field today. The document is written as a PDF, with internal links as well as links to MATLAB: A Quick Introduction for Scientists and Engineers (Rudra Pratap, ). are the modified versions of the items from Rudra Pratap's, Getting started with Matlab, helpdesk is the web browser-based help, including printable (PDF).
|Language:||English, Spanish, Indonesian|
|Genre:||Politics & Laws|
|ePub File Size:||21.47 MB|
|PDF File Size:||18.47 MB|
|Distribution:||Free* [*Regsitration Required]|
GETTING STARTED WITH MATLAB-RUDRAPRATAP - Free ebook download as PDF File .pdf), Text File .txt) or read book online for free. MATLAB. A Quick Introduction for Scientists and Engineers (Updated for MATLAB 6). Rudra Pratap Department of Mechanical Engineering Indian Institute of Science. MATLAB, which stands for MATrix LABoratory, is a state-of-the-art mathematical software The purpose of this tutorial is to familiarize the beginner to MATLAB, by introducing the Rudra Pratap, Saunders College Publishing,
If you need to store the les somewhere else, you might have to specify the path to the les using the path command, or change the working directory of MATLAB to the desired directory with the cd command. So, your commands might look dierent than those given. The same is true for hyperbolic functions. How to get a hardcopy of the graph. 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 diagram in Fig.
The coverage of topics is based on my experience of what is most useful. I did all the computations for my Ph. New versions of software packages usually add features that their experienced users ask for. I still loved it. I have given several introductory lectures. There are many examples. This update required checking each command and function given in this book as examples.
Although the graphics capability was limited to bare-bones 2-D plots. 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. It is not a complete miracle drug. I expect and enjoy interactive calculation. Vijay Arakeri. In fact. Konda Reddy. I thank my wife. The MathWorks Inc.
My editor Peter Gordon at Oxford University Press has always been supportive and kept his word on keeping the price of the book low. I greatly appreciate your words of encouragement. Sai Jagan Mohan. Ravi Bhusan Singh Pandaw. I have added more exercises in this edition. Yair Hollander. In addition. Rudra Pratap. It has been a struggle to keep this book lean and thin. Richard Rand. Christopher D. John T.
In response to emails I have received from several readers across the globe. I thank all students who have used this book in its past forms and provided constructive criticism.
Bangalore May. Greg Couillard. John Gibson. I was helped through the development of this book by the encouragement. James R. I have also been fortunate to receive feedback by email. Sesha Sai. I must acknowledge the help of three special people. David Caughey. Mike Coleman. I wish to thank Chris Wohlever. Andy Ruina has been an integral part of the development of this book all along.
John C. Despite their arrival.. I have also added substantial material in Chapter 3 Interactive Computation and Chapter 5 Applications. Yogendra Simha. That apart. I have tried hard to protect the interests of a new user in this book. Thomas Vincent. Thank you all. Les Axelrod. These Toolboxes are collections of functions written for special applications such as Symbolic Computation.
Introduction 1. The user. Best of all. It provides an interactive environment with hundreds of built-in functions for technical computation. Neural Networks. The diagram in Fig. Most of these functions use state-ofthe art algorithms. Control System Design. Image Processing. The fundamental data-type is the array.
There are numerous functions for 2-D and 3-D graphics as well as for animation. Once written. The built-in functions are. What is more. Software packages that do symbolic algebra are also known as Computer Algebra Systems.
See Section 8. Of course. For example. The bottom line is. There are more than universities and thousands of companies listed as registered users. There are other packages. MA Phone: Contact the company for product information and ordering at the following address: In addition to Windows. That is why this book exists — to help you overcome the fear. It takes a while to understand its real power.
UX Digital UNIX. All features are discussed through examples using the following conventions: The goal is to get started as simply as possible. Typing help category in MATLAB with the appropriate category name provides a list of functions and commands in that category. For almost all major topics. We believe this. Detailed help can then be obtained for any of those commands and functions. All examples are system-independent. The texts in the white boxes inside these gray boxes are explanatory notes.
Most of the examples are designed so that you can more or less follow them without reading the entire text. We discourage a passive reading of this book.
An array with m rows and n columns is a called a matrix of size m n. How to create row and column vectors. How to create a vector of n numbers linearly equally spaced between two given numbers a and b.
How to do simple arithmetic operations on vectors. How to do array operations: How to use trigonometric functions with array arguments. How to use elementary math functions such as square root, exponen- tials, and logarithms, with array arguments. 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.
If you have some background in linear algebra, you will nd that MATLAB is set up to do almost any matrix computation e. 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 Calculate the limit 1 1r and compare the computed sum s. 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. Extract the rst 10 elements of each row of the matrix, and display them as column vectors.
The last command M: Creating and Printing Simple Plots 29 2. Creating and Printing Simple Plots Goal: How to generate x and y coordinates of equidistant points on a unit circle. How to plot x vs y and thus create the circle. How to set the scale of the x and y axes to be the same, so that the circle looks like a circle and not an ellipse. How to label the axes with text strings.
How to title the graph with a text string. How to get a hardcopy of the graph. 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. To do this, rst generate the data x- and y-coordinates of, say, points on the circle , then plot the data, and nally print the graph.
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.
After you enter the command plot x,y , you should see an ellipse in the Figure Window. The next command axis equal , directs MATLAB to use the same scale on both axes, so that a circle appears as a circle. You can also use axis square to override the default rectangular axes. The arguments of the axis, xlabel, ylabel, and title commands are text strings. Text strings are entered within single right-quote. For more information on text strings, see Section 3.
The print command sends the current plot to the printer connected to your computer. A simple sine plot: Label the axes and put Plot created by yourname in the title.
Make the same plot as above, but rather than displaying the graph as a curve, show the unconnected data points. To display the data points with small circles, use plot x,y,o. You may peep into Section 6. An exponentially decaying sine plot: You need array multiplication between exp Space curve: If too much text ashes by the screen, type more on, hit return, and then type help plot again.
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. You can use plot x,y,x,z,-- or you can plot the rst curve, use the hold on command, and then plot the second curve on top of the rst one.
Fancy plots: Go to Section 6. Reproduce any of the plots you like.
A very dicult plot: 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. The le must be saved with a. A script le is executed by typing its name without the. For more information, see Section 4.
How to create, write, and save a script le. Unfortunately, creating, editing, and saving les are somewhat system dependent tasks. 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 know how to open, edit, and save a le.
You know which directory your le is saved in. Write a script le to draw the unit circle of Lesson You are essentially going to write the commands shown in Fig. Follow the directions below. Create a new le: On PCs and Macs: Select New M-File from the File menu. A new edit window should appear.
On Unix workstations: Type the following lines into this le. Write and save the le under the name circle. Select Save As A dialog box should appear. Type the name of the document as circle.
Click Save to save the le. You are on your own to write and save the le using the editor of your choice. Execute the file.
You should see the circle plot in the Figure Window. Executing a script le. Show the center of the circle: Modify the script le circle to show the center of the circle on the plot, too. See Exercises 2 and 7 of Lesson 3. Change the radius of the circle: Modify the script le circle.
Modify the x and y coordinate calculations appropriately. Save and execute the le. When asked, enter a value for the radius and press return. Variables in the workspace: All variables created by a script le are left in the global workspace.
You can get information about them and access them, too: Type who to see the variables present in your workspace. You should see the variables r, theta, x and y in the list. Type whos to get more information about the variables and the workspace. Type [theta x y] to see the values of , x and y listed as three columns. All three variables are row vectors. Typing a single right quote. Contents of the le: You can see the contents of an M-le without opening the le with an editor.
The contents are displayed by the type command. To see the contents of circle. H1 line: The rst commented line before any executable statement in a script le is called the H1 line. It is this line that is searched by the lookfor command. Since the lookfor command is used to look for M-les with keywords in their description, you should put keywords in H1 line of all M- les you create.
Does it list the script le you just created? Just for fun: Write a script le that, when executed, greets you, displays the date and time, and curses your favorite TA or professor.
See the on-line help on these commands before using them. Your changed script le should look like this: Here is a script le that you may not fully understand yet.
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: To learn how to write and execute a function le. Also, to learn the dierence between a script le and a function le. A function le is also an M-le, just like a script le, except it has a function denition line on the top that denes the input and output explicitly.
How to open and edit an existing M-le. How to dene and execute a function le. Write a function le to draw a circle of a specied radius, with the radius as the input to the function. You can either write the function le from scratch or modify the script le of Lesson 4. We advise you to select the latter option. Open the script le circle. Select Open M-File from the File menu. Navigate and select the le circle. Double click to open the le.
The contents of the le should appear in an edit window. Edit the le circle. Now write and save the le under the name circlefn.
Type the name of the document as circlefn. Click save to save the le. Here is a sample session that executes the function circlefn in three dierent ways. Try it out. You can also specify the value of the input directly. If you dont need the output, you dont have to specify it. Executing a function le.
Note that a function le see previous page must begin with a function denition line. To learn more about function les, refer to Section 4. The argument of the title command in this function le is slightly complicated.
To understand how it works see Section 3. Type help function to get on-line help on function. Read through the help le.
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: Write a function to compute the interest X X 0 on your account for a given X, n, r, and k.
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: How to nd your bearings in the jungle of directories. How to nd which of your M-les are accessible.
How to change the working directory. MATLAB 6 includes several menu driven features which make le navigation much easier compared to the earlier versions. 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? The rst thing to nd is which directory you are currently in. 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.
Make sure that after you change the directory, the new directorys name ap- pears in 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. These commands list all the les and folders in the current directory. So, if you dont do any di- rectory navigation, all les that you create and save during a MATLAB session will be saved in the work directory.
However, you are not lim- ited to this directory for saving your les. You can create a directory 44 Tutorial Lessons Figure 2. This change, however, is eective only for the duration of the current session. Create two new directories: Use command addpath to add these directories to the existing path. Working with Files and Directories 45 Type path on the command line to see the new MATLAB search path and check if your directories are included right on the top of the stack.
You can also use path command to add these directories to the search path. Alternatively, you can navigate and get your desired directory to the Current Directory subwindow, right-click the mouse inside that subwindow to bring up a pull down menu, and select add to path to add the directory to the search path. 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. Command History subwindow: Click on the tab for this subwin- dow if it is not already in the foreground.
Type the following commands in the command window. Select all the four commands shown above in the Command History window, right click the mouse, and select Create M- File. Thus you can test commands and turn them into M-les easily. Workspace subwindow: Click on the tab for this subwindow if it is not already in the foreground.
Select any of the variables, t, x, or y, listed in this subwindow and double click to open an Array Editor window. You can change any values in the array here.
Select any variable and right click the mouse. Select any option from the pop-up menu. You can edit, import, graph, or save the variable with a click of the mouse. Interactive Computation In principle, one can do all calculations in MATLAB interactively, by enter- ing commands sequentially in the command window, although a script le explained in Section 4. The interactive mode of computation, how- ever, makes MATLAB a powerful scientic calculator that puts hundreds of built-in mathematical functions for numerical calculations and sophisticated graphics at the nger tips of the user.
In this chapter, we introduce you to some of MATLABs built-in functions and capabilities, through examples of interactive computation.
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: If your command does not t on one line you can continue the command on the next line if you type three consecutive periods at the end of the rst line.
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. Af- ter the rst letter, any number of digits or underscores may be used, but MATLAB remembers only the rst 31 characters.
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 output appearance of oating point numbers number of digits after the decimal, etc. 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: If you need to save some of the com- puted results for later processing, you can save the variables in a le in binary or ASCII format with the save command. How to print your work: The simplest way, perhaps, is to create a diary with the diary command see Section 3.
Then you can print the diary just the way you would print any other le on your computer. Before you print, make sure that the command window is the active window. If it isnt, just click on the command window to make it active. 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. A scalar does not need brackets. 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.
MATLAB, however, provides a much higher level of index specication it allows a range of rows and columns to be specied at the same time. For example, the statement A m: When the rows or columns to be specied range over all rows or columns of the matrix, a colon can be used as the row or column index. Thus A: This feature makes matrix manipulation much easier and provides a way to take advantage of the vectorized nature of calculations in MATLAB.
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.
Thus if A is a 10 10 matrix, B is a 5 10 matrix, and y is a 20 elements long row vector, then A [1 3 6 9],: In such manipulations, it is imperative, of course, that the sizes of the submatrices to be manipulated are compatible. For example, in the above assignment, number of columns in A and B must be the same, and the total number of rows specied on the right hand side must be the same as the number of rows specied on the left.
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: As a dierently sized matrix: Thus, for a 6 6 matrix A, reshape A,9,4 transforms A into a 9 4 matrix, reshape A,3,12 transforms A into a 3 12 matrix. Now let us look at some frequently used manipulations.
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. Share this link with a friend: Other Related Materials 29 pages.