GETTING STARTED WITH MATLAB-RUDRAPRATAP - Free ebook download as PDF File .pdf), Text File .txt) or read book online for free. MATLAB. The purpose of this tutorial is to familiarize the beginner to MATLAB, by introducing Published Books Rudra Pratap, Saunders College Publishing, 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, German, Dutch|
|ePub File Size:||16.70 MB|
|PDF File Size:||8.46 MB|
|Distribution:||Free* [*Registration needed]|
The document is written as a PDF, with internal links as well as links to online This book includes plenty of exercise activities - more than can usually be MATLAB: A Quick Introduction for Scientists and Engineers (Rudra Pratap, ). Rudra Pratap is the author of Getting Started with MATLAB 7 ( avg rating, ratings, 5 reviews, Rudra Pratap's Followers (2) Rudra Pratap's books. Download Rudra Pratap Matlab Pdf Free. 2/15/ MATLAB, a software package for high-performance numerical computation and  Merrill I. Skolnik, Introduction to radar systems, McGraw Hill Book Company Inc.,
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?
Getting Started with MATLAB
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.
Matlab rudrapratap - Getting Started with MATLAB A Quick...
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.
Transpose The transpose of a matrix A is obtained by typing A, i. 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. The initialization reserves for the matrix a contiguous block in the computers memory. Matrix operations performed on such matrices are generally more ecient. 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: For example, eye m,n returns an m by n matrix with 1s on the main diagonal zeros m,n returns an m by n matrix of zeros ones m,n returns an m by n matrix of ones rand m,n returns an m by n matrix of random numbers randn m,n returns an m by n matrix of normally distributed numbers diag v generates a diagonal matrix with vector v on the diagonal diag A extracts the diagonal of matrix A as a vector diag A,1 extracts the rst upper o-diagonal vector of matrix A.
The rst four commands with a single argument, e. For example, eye 3 produces a 3 3 identity matrix. 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. Special vectors, such as vectors of zeros or ones of a specic length, can be created with the utility matrix functions zeros, ones, etc.
In all the above commands if B is replaced by a scalar, say , the arith- metic operations are still carried out. 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.
Although these operations are usually used in conditional statements such as if-then-else to branch out to dierent cases, they can be used to do pretty sophisticated matrix manipulation.
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. A row vector x times a column vector x of the same length gives the inner product, which is a scalar 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. But what about A? Clearly, these are array operations. You can, however, also compute matrix exponential e A , matrix square root A, etc. 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. All character strings are entered within two single right quote characters string. 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. Examples of dierences between matrix functions and array functions. Text strings of dierent lengths can be made to be of equal length by padding them with blanks. 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.
For a quote within a string you must use the double quote character. 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. Such text objects are particularly useful in creating titles for gures and other graphics annotation commands see Section 6. For example, suppose you want to produce a few variance-study graphs with dierent values of the sample size n, an integer variable.
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. One use of this function is in creating or loading sequentially numbered data les.
For example, you can use eval to run a set of commands ten times while you take a two-hour lunch break. The following script runs the set of commands ten times and saves the output variables in ten dierent les. So read them carefully. The last command eval 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 square brackets inside the eval command are used here to produce a single string by concatenating three individual strings. The brackets are not a part of the eval command. Note the blank spaces in the strings save and xyz. 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. We frequently need to evaluate such functions in scientic calculations. One way to evaluate such functions is by programming them in Function-les see Section 4. However, there is a quicker way of programming functions if they are not too complicated. This is done by dening inline functionsfunctions that are created on the command line. You dene these functions using the built-in function inline.
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.
Examples of creating and using inline functions. There is on-line help for all built-in functions. With so many built-in functions, it is important to know how to look for functions and how to learn to use them.
There are several ways to get help: If you know the exact name of a function, you can get help on it by typing help functionname on the command line. For example, typing help help provides help on the function help itself.
If you are looking for a function, use lookfor keyword to get a list of functions with the string keyword in their description. For example, typing lookfor identity matrix lists functions there are two of them that create identity matrices. If you want to look around and get a feel for the on-line help by clicking and navigating through what catches your attention, use the window based help, helpwin.
A Quick Introduction for Scientists and Engineers
To acti- vate the help window, type helpwin at the command prompt or select Help Window from the Help menu on the command window menu bar. If you like to read on-line documentation and get detailed help by clicking on hyperlinked text, use the web browser based help facility, helpdesk. To activate the help window, type helpdesk at the command prompt or select Help Desk from the Help menu on the command window menu bar.
As you work more in MATLAB, you will realize that the on-line help with the command help and keyword search with lookfor are the easiest and the fastest to get help. Typing help by itself brings out a list of categories see Fig. You can get help on one of these categories by typing help category. For example, typing help elfun gives a list of elementary math functions with a very brief description of each function. Further help can now be obtained on a function because the exact name of the function is now known.
Control flow. Detailed help can then be obtained by typing: It lets you specify a descriptive word about the function for which you need help. The following examples take you through the process of looking for help, getting help on the exact function that serves the purpose, and using the function in the correct way to get the results.
MATLABs help command is not forgiving of any typos or misspellings, and hence you must know the exact command name. Finding the determinant of a matrix We have a 10 10 matrix A e. We do not know if the command for determinant is det, deter, or determinant.
Then we can nd the exact syntax of the command or function. As is evident from the help on det in Fig. DET Symbolic matrix determinant. DET X is the determinant of the square matrix X. See also COND. To find the function, use the keyword search command lookfor. Example of how to nd the function that computes the determi- nant of a matrix. Finding eigenvalues and eigenvectors Suppose we are interested in nding out the eigenvalues and eigenvectors of a matrix A, but we do not know what functions MATLAB provides for this purpose.
Since we do not know the exact name of the required function, our best bet to get help is to try lookfor eigenvalue. EIG Eigenvalues and eigenvectors. EXPM3 Matrix exponential via eigenvalues and eigenvectors. QZ Generalized eigenvalues. EIGS Find a few eigenvalues and eigenvectors of a matrix EIG X is a vector containing the eigenvalues of a square matrix X. Detailed help can then be obtained on any of the listed files with help. Example of use of on-line help.
You can then browse through the list, choose the function that seems closest to your needs, and ask for further help on it.
In Fig. The on-line help on eig tells us what this function does and how to use it. The names of the output or the input variables can, of course, be anything we choose. Although its obvious, we note that the list of the variables input or output must be in the same order as specied by the function.
Specifying an explicit list of output variables [eigvec,eigval] gets the eigenvectors of A in the matrix eigvec and the eigenvalues of A on the diagonal of the matrix eigval.
Examples of use of the function eig to nd eigenvalues and eigenvectors of a matrix. All built-in functions in MATLAB use low- ercase letters for their names, yet the help on any function lists the function in uppercase letters, as is evident from Figs.
For the rst-time user, it may be frustrating to type the command exactly as shown by the help facility, i. On-line help can be obtained by typing help commands on the com- mand line, as we have described in the foregoing section. In addition, on some computers such as Macintosh and IBM compatibles with Win- dows, on-line help is also available on the menu bar under Help. The menu bar item gives options of opening Help Window, a point and click interactive help facility, or Help Desk, a web browser based extensive help facility.
Although lookfor is a good command to nd help if you are uncertain about the name of the function you want, it has an annoying drawback: So typing lookfor linear equations causes an error but lookfor linear equations is ok , while both lookfor linear and lookfor equations do return useful help.
The most direct way is to use the save and load commands. You can also save a session or part of a session, including data and commands, using the diary command. We will describe save and load first. Mat-les are written in binary for- mat with full 16 bit precision. It is also possible to write data in Mat-les in 8-digit or digit ASCII format with optional arguments to the save com- mand see the on-line help.
Mat-les must always have a. Examples of proper usage of these commands are as follows: For more information, see the on-line help on load.
The easiest way to import data from a le is to invoke the import wizard by either i selecting Import Data from the File menu of the MATLAB window or ii typing uiimport on the command line, and then following the instructions on the screen.
The import wizard does an excellent job of recognizing most le formats, separating data into numeric-data and text- data, and loading the data in MATLAB workspace. Import wizard can load data from several le formats used for text data, spreadsheet data. See on-line help on fileformats to see a list of readable le formats. Alternatively, you can also import data from a le using the built-in func- tion importdata filename from the command line.
The lename must include the le extension e. A le name with any extension can be specied as the output le. For example, typing diary session1. The recording is terminated by the command diary off. The same diary le can be opened later during the same session by typing diary on.
This will append the 76 Interactive Computation subsequent part of the session to the same le session1. All the g- ures in this book that show commands typed in the command window and consequent MATLAB output were generated with the diary command. Diary les may be opened and modied with any standard text editor. To do this, we must rst edit the diary le to remove all unwanted lines for example, MATLAB error messages and output generated by commands, and then we must rename the le with a.
Now, we can execute the le by typing the name of the le without the. This will execute all the commands in the diary le. Thus, it is also possible to load the values of a variable that were written explicitly in a diary le. If the variables were from an array, we would need to enclose them in square brackets, and assign this to a variable.
Values loaded this way will have only the precision explicitly written in the diary le. The number of digits of a variable recorded in the diary depends on the format in use during the session for a description of format, see Section 1. The diary is a good way of recording a session to be included in reports or to show someone how a particular set of calculations was done.
As an alternative to the diary facility, you can scroll through the com- mand window and copy the cut-and-paste method the parts you want to a text le. Be warned, however, that this facility has not been very reliable in the past because of cross compatibility problems between the various versions of MATLAB and Word. The commands to produce simple plots are surprisingly sim- ple. For complicated graphics and special eects there are a lot of built-in functions that enable the user to manipulate the graphics window in many ways.
Unfortunately, the more control you want the more complicated it 3. We describe the graphics facility in more detail in Chapter 6. The most direct command to produce a graph in 2-D is the plot com- mand.
If a variable ydata has n values corresponding to n values of variable xdata, then plot xdata,ydata produces a plot with xdata on the hori- zontal axis and ydata on the vertical axis. To produce overlay plots, you can specify any number of pairs of vectors as the argument of the plot com- mand.
We discuss more of this, and much more on other aspects of plotting, in Chapter 6. This function could also be plotted using fplot, a command for plotting functions of a single variable. Thus, in the command plot x1,y1,x2,y2 , x1, and y1 must have the same 78 Interactive Computation length, x2, and y2 must have the same length, while x1, and x2 may have dierent lengths.
There are several other plotting functions which are easy to use and quick to produce plots if you are plotting a function: It takes the function of a single variable and the limits of the axes as the input and produces a plot of the function. The simplest syntax there is more to it, see the on-line help is fplot function,[xmin xmax] Example: Example of plotting a function with fplot.
These functions require the user to specify the function to be plotted as an input argument. The function to be plotted can be specied as a character string or as an inline-function.
There is a default domain for each ez-plotter but you have the option of overwriting the default domain. These plotting functions are really easy to use. Take a quick look at the following examples.
You can also use ezplot with implicit functions i. See on-line help on ezplot. Example of plotting a function with ezplot. This is the polar version of ezplot. It takes r as the input argument. The plot produced is shown in Fig. Contour plots are a breeze with this function. Plot of a 3-D parametric space curve with ezplot3.
This is just a variant of ezcontour. It produces lled con- tours.
The syntax is the same as for ezcontour. For dierent ranges of x and y, the domain can be specied by a 1-by-4 vector, [xmin, xmax, ymin, ymax]. An even prettier looking variant of ezsurf is ezsurfc which combines the surface plot with its contour plot. There are two more functions in the ez-stable, ezmesh and ezmeshc, that are used for 3-D plotting. These functions work exactly like the surface plotting functions except that they create the 3-D graphs with wireframe meshes rather than with surface patches.
Entering matrices: Enter the following three matrices. Check some linear algebra rules: Is matrix addition commutative? Are the results the same? Is matrix addition associative? Is multiplication with a scalar distributive? Is multiplication with a matrix distributive? Matrices are dierent from scalars! Is that true for matrices?
In general, matrix products do not commute either unlike scalar prod- ucts. Create matrices with zeros, eye, and ones: Create the following matri- ces with the help of the matrix generation functions zeros, eye, and ones.
See the on-line help on these functions if required e. Create a big matrix with submatrices: The following matrix G is created by putting matrices A, B, and C given above, on its diagonal.
In how many ways can you create this matrix using submatrices A, B, and C that is, you are not allowed to enter the non-zero numbers explicitly? Manipulate a matrix: Do the following operations on matrix G created above in 4. Delete the last row and last column of the matrix. Extract the rst 4 4 submatrix from G.
What do you get if you type G 13 and hit return? See the structure of a matrix: Now replace the 10 10 submatrix between rows 6: See the structure of the matrix in terms of nonzero entries with the command spy A. Set the 5 5 submatrices in the top right corner and bottom left corner to zeros and see the structure again. Create a symmetric matrix: Create an upper triangular matrix with the following command: Make sure you understand how this command works see the on-line help on diag if required.
Now use the upper o-diagonal terms of A to make A a symmetric matrix with the following command: This is a somewhat loaded command. It takes the upper triangular part of A above the main diagonal, ips it transposes , and adds to the original matrix A, thus creating a symmetric matrix A. See the on-line help on triu.
Do some cool operations: Now do the following operations. Extract all 30 a ij 50 in a vector b, that is, nd all elements of A that are between 30 and 50 and put them in a vector b. How about some fun with plotting? Scripts and Functions For on-line help type: In some regards, it is a higher-level language than most common programming languages, such as Pascal, Fortran, and C, meaning that you will spend less time worrying about formalisms and syntax.
They are called M-les because they must have a. M-les can be created using any editor or word processing application. There are two types of M-lesscript les and function les. Now we discuss their purpose and syntax. A script le is executed by typing the name of the le without the.
Naturally, script les work on global variables, that is, variables currently present in the workspace. Results obtained from executing script les are left in the workspace. Scripts and Functions A script le may contain any number of commands, including those that call built-in functions or functions written by you. Script les are useful when you have to repeat a set of commands several times. Here is an example. Example of a Script File: Let us write a script le to solve the following system of linear equations: Clearly, A depends on the parameter r.
We want to nd the solution of the equation for various values of the parameter r. We also want to nd, say, the determinant of matrix A in each case. How you create this le, write the commands in it, and save the le, depends on the computer you are using. In any case, you are creating a le called solvex. Therefore, the results of these commands will be displayed on the screen when we execute the script le. The results will be stored in variables det A and x, and these will be left in the workspace.
Even though the output of solvex is only det A and x, A and b are also there in your workspace, and you can see them after execution of solvex by typing their names at the MATLAB prompt. So, if you want to do a big set of computations but in the end you want only a few outputs, a script le is not the right choice.
What you need in this case is a function le. NEVER name a script le the same as the name of a variable it com- putes. Thus, if you execute a script le xdot. Now if you change something in the script le and execute it again, all you get is the old value of xdot! Your changed script le is not executed because it cannot be accessed as long as the variable xdot exists in the workspace. The name of a script le must begin with a letter. The rest of the characters may include digits and the underscore character.
You may not use any periods in the name other than the last one in. Thus, names such as project 23C. Be careful with variable names while working with script les, because all variables generated by a script le are left in the workspace, unless 88 Programming in MATLAB: Scripts and Functions you clear them. Avoid name clashes with built-in functions. It is a good idea to rst check if a function or script le of the proposed name already exists. You can do this with the command exist name , which returns zero if nothing with name name exists.
Function les are like programs or subroutines in Fortran, procedures in Pascal, and functions in C. Once you get to know MATLAB well, this is where you are likely to spend most of your time writing and rening your own function les. A function le begins with a function denition line, which has a well- dened list of inputs and outputs.
Without this line, the le becomes a script le. The syntax of the function denition line is as follows: For example, if the name of the function is projectile it must be written and saved in a le with the name projectile.
The function denition line may look slightly dierent depending on whether there is no output, a single output, or multiple output. The rst word in the function denition line, function, must be typed in lower case. A common mistake is to type it as Function. All comment lines immediately following the function denition line are displayed by MATLAB if help is sought on the function. The very rst comment line immediately following the denition line is called the H1 line.
An H1 line, if present, is automatically cataloged in the Contents. This allows the line to be referenced by the lookfor command. A word of caution: A single-output variable is not required to be enclosed in square brack- ets in the function denition line, but multiple output variables must be enclosed within [ ]. When there is no output variable present, the brackets as well as the equal sign may be omitted see examples above. Input variable names given in the function denition line are local to the function, so other variable names or values can be used in the function call.
The name of another function can also be passed as an input variable. No special treatment is required for the function names as input variables in the function denition line. However, when the function is executed, the name of the input function must be passed as a character string, i.
Scripts and Functions 1. With explicit output: This is the full syntax of calling a function. Both the output and the input list are specied in the call. The third input variable must be assigned a default value inside the function if it is required in calculations.
The output corresponds to the rst two elements of the output list of motion. Without any output: The output list can be omitted entirely if the computed quantities are not of any interest.
This might be the case when the function displays the desired result graphically. To execute the function this way, just type the name of the function with the input list. For example, motion xt,yt,time ; will execute the function motion without generating any explicit output, provided that xt, yt, and time are dened, of course.
If the semicolon at the end of the call statement is omitted, the rst output variable in the output-list of the function is displayed in the default variable ans. A function can be written to accept a partial list of inputs if some default values of the other unspecied inputs is dened inside the function.
This kind of input list manipulation can be done with the built-in function nargin, which stands for number-of-arguments-in. Similarly, the list of output can be manipulated with the built-in function nargout.
See the on-line help on nargin and nargout. For an example of how to use them, look at the function fplot by typing type fplot. Example of a Simple Function File: Let us write a function le to solve the same system of linear equations that we solved in Section 4. This time, we will make r an input to the function and det A and x will be the output. Let us call this function solvexf.
As a rule, it must be saved in a le called solvexf. Now r, x and det A are all local variables. Therefore, any other variable names may be used in their places in the function call statement. After execution of a function, the only variables left in the workspace by the function will be the variables in the output list.
This gives us more control over input and output than we can get with script les. We can also include error checks and messages inside the function. For example, we could modify the function above to check if matrix A is empty or not and display an appropriate message before solving the system, by changing the last line to: Scripts and Functions For a description of if-elseif-else branching and other control ow commands, see Section 4.
The variables inside a function are local and are erased after execution of the function. Functions can have arguments, script les do not. What about functions inside another function? Are they local? How are they executed? Can a function be passed as an input variable to another function? Now we address these questions.
Executing a function inside another function Usually, it is a straightforward process, so much that you do not have to pay any special attention to it. In the function solvexf above, we used a built-in function, det, to calculate the determinant of A. This is true for all functions, built-in or user-written. The story is dierent only when you want the function name to be dynamic, that is, if the function to be executed inside may be dierent with dierent executions of the calling function 2.
In such cases, the actual name of the function is passed to the calling function through the input list and a dummy name is used inside the calling function. For example, on Unix systems, typing! The commands lookfor, help, helpwin, and helpdesk provide on-line help. See Section 3. The program includes a tutorial introduction that is worth trying. In addition, it can read input files and write output files see Section 4.
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 dimension statements are required for vectors or arrays. You can find the dimensions of an existing matrix or a vector with the size and length for vectors only commands. Thus a and A are different variables. You can turn case sensitivity on and off with the casesen command.
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. Output format: Though computations inside MATLAB are performed using double precision, the appearance of floating point numbers on the screen is controlled by the output format in use. There are several different screen output formats. 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. These commands can be recalled with the up-arrow key. This helps in editing previous commands. You can also recall a previous command by typing the first few characters and then pressing the key. Alternatively, you can copy and paste commands from the Command History subwindow where all your commands from even previous sessions of MATLAB are recorded and listed.
There are two types of these files: script files and function files see Section 4. Some built-in functions are provided with source code in readable M-files so that they can be copied and modified. Mat-files are binary data-files, with a. Almost all commands work the same way.
The only commands that differ are the ones that necessarily depend on the local operating system, 20 1. The user interface how you interact with your computer , however, may vary a little from platform to platform. On Unix machines: Type matlab on the Unix prompt and hit return. If it is not, ask your system administrator. You can save all your work in this folder and access all your files easily default set-up. If not, you have to create a separate folder for saving your work.
The most convenient place, however, to save all user-written files is in a directory or folder immediately below the directory or folder in which the MATLAB application program is installed for PCs. If you need to store the files somewhere else, you might have to specify the path to the files using the path command, or change the working directory of MATLAB to the desired directory with the cd command.
We recommend the latter. If you are not allowed to write in the MATLAB folder as may be the case in some shared facilities , then create a folder where you are allowed perhaps on your own floppy disk , copy the file startup. You should also personalize the Startup file by editing it and adding a line, say, disp Hello Kelly, Welcome Aboard. To open, write, and save M-files, use a text editor such as vi or emacs.
Printing: On PCs: To print the contents of the current active window command, figure, or edit window , select Print For example, to print the file startup.
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.
The Current Directory is shown just above the Command Window with the option of changing the current directory with just a click of the mouse. In addition, there is a Current Directory subwindow to the left of the Command Window that lists files in the current directory, gives you options of opening, loading a. Use dir or ls at the command prompt to see if MATLAB lists your files or click on the Current Directory tab to the left of the command window to see the listing of files in that subwindow.
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. Not overwriting an existing file while editing: You run your program by executing your M-file, do not like the result, edit the file, and run it again; but MATLAB gives the same answer!
This can happen due to various reasons. Simple cure is, clear the workspace with clear all and execute your file. 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 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. So, your commands might look different than those given. Before You Start You need some information about the computer you are going to work on. In particular, find out: How to switch on the computer and get it started. How to log on and log off. Where you can write and save files hard drive or a floppy disk.
If there is a printer attached to the computer. 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! Key features: Learn to add, multiply, and exponentiate numbers, use trig functions, and control screen output with format. Lesson Create and work with arrays, vectors in particular.
Key features: Learn to create, add, and multiply vectors, use sin and sqrt functions with vector arguments, and use linspace to create a vector. Lesson Plot simple graphs. Key features: Learn to plot, label, and print out a circle. Lesson Write and execute a script file. Key features: Learn to write, save, and execute a script file that plots a unit circle. Lesson Write and execute a function file. Key features: Learn to write, save, and execute a function file that plots a circle of any specified radius.
Lesson Learn about file and directory navigation. Time Estimates: Lesson: 10 minutes Exercises: 30 minutes What you are going to learn: How to do simple arithmetic calculations. How to assign values to variables. How to suppress screen output. How to control the appearance of floating point numbers on the screen. Some commands and their output are shown below. Go ahead and reproduce the results. Note that the result of an unassigned expression is saved in the default variable ans.
You can also assign the value of an expression to a variable. Here are two examples. You can also quit by selecting quit from the file menu on Macs and PCs.
Figure 2. Arithmetic operations: Compute the following quantities: and compare with 1 1 1. Exponential and logarithms: The mathematical quantities e x, ln x, and log x are calculated with exp x , log x , and log10 x , respectively. Calculate the following quantities: e 3, ln e 3 , log 10 e 3 , and log 10 10 5. 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. 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? Can you explain the difference between the two results? 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. An array with m rows and n columns is a called a matrix of size m n. Time Estimates: Lesson: 15 minutes Exercises: 45 minutes What you are going to learn: 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 arithmeticoperations on vectors. How to do array operations:.
How to use trigonometricfunctions with array arguments. How to use elementary math functions such as square root, exponentials, 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 find 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. You can add or subtract two vectors of the same size. But you cannot add or subtract a row vector to a column vector. You can multiply or divide the elements of two same-sized vectors term by term with the array operator.The Figure and the Editor windows appear only when invoked with the appropriate commands.
T i and T f , specifying the lower and upper range of the table in Celsius. For example, to print the le startup. For dierent ranges of x and y, the domain can be specied by a 1-by-4 vector, [xmin, xmax, ymin, ymax].
You can use any text editor to carry out these tasks. The inverse function atan2 takes 2 arguments, y and x, and gives the four-quadrant inverse tangent.