# Computing with MATLAB Matlab Help

This section provides an overview of the computational capabilities of MAT LAB, and points out where in the book these capabilities are discussed in more detail. The following chapters also provide numerous self-help exercises and examples of how these features can be used to solve engineering problems.

Arrays

MATLAB has hundreds of functions, which we will discuss throughout the text. For example, to compute sin x, where x has a value in radians, you type sin (x) . To compute cos x, type cos (x) . The exponential function e× is computed from exp (x) , The natural logarithm, In x, is computed by typing log (x) . (Note the spelling difference between mathematics text, In, and MAlLAB syntax, log.) You compute the base 10 logarithm by typing Log (x). The inverse sine, or arcsine, is obtained by typing asin (x) . It returns an answer in radians, not degrees.

One of the strengths of MATLAB is its ability to handle collections of numbers, called arrays, as if they were a single variable. A numerical array is an ordered collection ofnumbers (a set of numbers arranged in a specific order). An example of an array Vi’able is one that contains the numbers 0, 1, 3, and 6, in that order. We can us sq~are brackets to define the variable x to contain this collection by typing x – [\$, 1, 3, 6). The elements of the array, must be separated by commas or spaces. Note that the variable y defined as y = [ 6 , 3, 1, 0] is not the same as ~ because the order is different.

We can add the two arrays x and y to produce another array z by typing the single line z = x + y. To compute z, MATLAB adds all the corresponding 6, 4, 4, 6. In most other programming languages, this operation requires more than one command. Because of this capability for handling arrays, MATLAB programs can be very short. Thus they are easier to create, read. and document.

You need not type all the numbers in the array if they are regularly spaced Instead, you type the first number and the last number. with the spacing in the middle, separated by colons.For example the numbers 0,0.1,0,2……..10 can be assigned to the variable u by typing u = [0:0,1:10].

To compute w = 5 sin u for u = 0, 0.1,0.2, … , 10, the session is:

»u = [0: 0 . 1 : 101 ;
»w = 5*sin (u) ;

The single line,w = 5*sin(u),computed the formula w =5 sinu 101 times once for each value in the array u, to produce an array z that has 101 values. This illustrates some of the power of MATLAB to perform many calculations with a few commands.

Because you typed a semicolon at the end of each line in the above session MATLAB does not display the results on the screen. The values are stored in the variables U and w if you need them. You can see all the U values by typing u after the prompt or, for example, you can see the seventh value by typing u (?). You can see the w values the same way. The number 7 is called an array index because it points to a particular element in the array.

» u (7)
ans =
0.6000
» w (7)
ans =
2.8232

You can use the length function to determine how many values are in an array. For example, continue the previous session as follows:

» m = length (w)
m =
101

Arrays that display on the screen as a single row of numbers with more than one column are called row arrays. You can create column arrays, which have more than one row, by using a semicolon to separate the rows.

Polynomial Roots

We can describe a polynomial in MATLAB with an array whose elements are the polynomial’s coefficients, starting with the coefficient of the highest power of x. For example, the polynomial 4x³ – 8x² + 7x – 5 would be represented by the array  (4, – 8, 7, – 5) . The roots of the polynomial ƒ(x) are the values of x ƒ(x) = O. Polynomial roots can be found with the roots (a) function, where a is the polynomial’s coefficient array. The result is a column array that contains the polynomial’s roots. For example, to find the roots of x³ – 7x² +40x – 34 = 0, the session is The roots are x = 1 and x = 3 ± 5i. The two commands could have been combined into the single command roots ( [1, -7 140 1-34] ).
Roots of functions other than polynomials can be obtained with the fzero function, covered.
Useful applications of arrays are discussed in more detail.

Built-in and User-Defined Functions

We have seen several of the functions built in to MATLAB, such as the sqrt and the s in functions. Table 1.3-1 lists some of the commonly used functions. Gives extensive coverage of the built-in functions.

MATLAB users can create their own functions for their special needs. Creation of user-defined functions is covered.

Working with Files

MATLAB uses several types of files’ that enable you to save programs, data, and session results. As we willsee in Section 1.4, MATLAB function files and program files are saved with the extension . mat and thus are called M-files.
MAT-files have the extension. mat and are used to save the names and values of variables created during a MATLAB session.

ASCII files are files written in a specific format designed to make them usable to a wide variety of software. The ASCII abbreviation stands for American Standard Code for Information Interchange. M-files are ASCII files that are written in the MATLAB language. Because they are ASCII files, M-files can be created using just about any word processor-generically called a text editor because the ASCII file format is the basic format that all word processing programs can recognize and create. M-files are machine independent. MAT-files are binary files, not ASCII files. Binary files are generally readable only by the software that created them, so you cannot read a MAT-file with a word processor. In general, transferring binary files between machine types (MS Windows and Macintosh, for example) is not easy. However, MAT-files contain a machine signature that allows them to be transferred. They can also be manipulated by programs external to MATLAB. Binary files provide more compact storage than ASCII files.
The third type of file we will be using is a data file, specifically an ASCII data file, that is, one created according to the ASCII format. You may need to use MATLAB to analyze data stored in such a file created by a spreadsheet program, a word processor, or a laboratory data acquisition system or in a file you share with someone else.

Saving and Retrieving Your Workspace Variables

If you. want to stop using MATLAB but continue the session at a later time, you must use the save and load commands. Typing save causes MATLAB to save the workspace variables, that is, the variable names, their sizes, and their values, in a binary file called matlab. mat, which MATLAB can read. To retrieve your workspace variables, type load. You can then continue your session as before of course, if you exited MATLAB after using the save command, you cannot recover your keystrokes or the MATLAB responses. To save the workspace variables in another file named filename. mat, type.save filename. To load the workspace variables, type load filename; this loads all the workspace variables from the file filename .mat. If the saved MAT-file filename contains the variables A,B, and C, then loading the file filename places these variables back into the workspace. If the variables already exist in the workspace, they are overwritten with the values of the variables from the file filename.

To load the workspace variables, the filename must have the extension .mat or no extension at all. If the file name does not have an extension, MATLAB assumes that it is mat.

To save just some of your variables, say, var1 and var2, in the file filename .mat, type save filename var1 var2. You need not type the variable names to retrieve them; just type load filename.

You can save the variables in ASCII single-precision (eight digits) format by typing save filename -ASCII. To save the variables in ASCII double precision (16 digits) format, type save filename double. ASCII files containing single-precision data are recognizable by their use of the E format to represent numbers. For example, the number 1.249 x 102 is represented as 1. 2,49E+002. ASCII files containing double-precision data use the D format;  for example, 1. 249D+002. As an alternative to the save function, you can, select Save Data from the File menu in the Command window. You can also save variables from the Workspace Browser.

Directories and Search Path It is important to know the location of the files you use with MATLAB. File location frequently causes problems for beginners. Suppose you use MATLAB on your home computer and save a file to a removable disk, as discussed later in this section. If you bring that disk to use with MATLAB on another computer, say tool’s computer lab, you must make sure that MATLAB knows how to find your files. Files are stored in directories, called folders on some computer systems, Directories can have subdirectories bylaw them. For example, suppose MATLAB was installed on drive c: in the The path’tells us and MATLAB how to find a particular file. For example, the file solve. mis a function in the Symbolic Math toolbox. The path to this file is c:\matlab\ toolbox\symbolic. The full name of a file consists of its path and its name, for example, c:\matlab\toolbox\symbolic\soIve.m.

Working with Removable Disks In Section 1.4 you will learn how to create and save M-files. Suppose you have saved the file problem1 .min the directory homework on a disk, which you insert in drive a:. The path for this file is a:\homework. As MATLAB is normally installed, when you type problem,

1. MATLAB first checks to see if problem1 is a variable and if so, displays its value.
2. If not, MATLAB then checks to see if problem1 is one of its own commands, and executes it if it is.
3. If not, MATLAB then looks in the current directory for a file named problem1 .m and executes problem1 if it finds it.
4. If not, MATLAB then searches the directories in its search path, in order, for problem1 .m and then executes it if found.

You can display the MATLAB search path by typing path. If problem1 is on the disk only and if directory a: is not in the search path, MATLAB will not find the file and will generate an error message, unless you tell it where to look. You can do this by typing cd a:\homework, which stands for “change directory to a:\ homework.” This will change the current directory to a: \homework and

force MATLAB to look in that directory to find your file. The general syntax of this command is cd dirname, where dirname is the full path to the directory. The main directory on the disk is a:, so if your file is in the main directory, be sure to include the colon, and type cd a:

An alternative to this procedure is to copy your file to a directory on hard drive that is in the search path. However, there are several pitfalls with approach: (I) if you change the file during your session, you might forget to copy the revised file back to your disk; (2) the hard drive becomes cluttered (this is a  problem in public computer labs, and you might not be permitted to save file on the hard drive); (3) the file might be deleted or overwritten if MATLAB reinstalled; and (4) someone else can access your work!

You can determine the current directory (the one where MATLAB look for your file) by typing pwd. To see a list of all the files in the current directory. type dir. To see the files in the directory dirname, type dir dirname.

The what command displays a list of the MATLAB-specific files in current directory. The what dirname command does the same for the dire dirname.

You can add a directory to the search path by usisg the addpath command To remove a directory from the search path, use the path command. Set Path tool is a graphical interface for working with files and directories. path tool to start the browser. To save the path settings, click on Save tool. To restore the default search path, click on Default in the browser.
These commands are summarized in Table 1.3-2.

Decision-Making Programs in MATLAB

The usefulness of MATLAB greatly increases with its ability to use making functions in its programs. These functions enable you to write program whose operations depend on the results of calculations made by the program MATLAB also can use loops to perform calculations repeated , a specified  number of times, or until some condition is satisfied. This allows problems of great complexity or problems required  numerous calculations.

Section 1.6 gives an introduction to these topics covers them in greater detail.

Plotting with MATLAB

MATLAB contains many powerful functions for easily creating plots of several different types, such as rectilinear, logarithmic, surface, and contour plots. As a simple example, let us plot the function y = sin 2x for 0 ≤ x ≥ 10. We choose to use an increment of 0.01 to generate a large number of x values in order to produce a smooth curve. The function plot (x,y) generates a plot with the x values on the horizontal axis (the abscissa) and the y values on the vertical axis (the ordinate). The session is:

»x = [0: 0.02: 8);
»y = 5*sin (x) i
»plot (x,y), xlabel (‘x’) ,ylabel (‘y’)

The plot appears on the screen in a graphics window; named Figure No.1, as shown in Figure 1.3-1. The xlabel function places the text in single quotes as a label on the horizontal axis. The ylabel function performs a similar function

for the vertical axis. When the plot command is successfully executed, a graphics Window automatically appears. If. a hard copy of the plot is desired, the plot can be printed by selecting Print from the File menu on the graphics window. The window can be closed by selecting Close on the File menu in the graphics window. You will then be returned to the prompt in the Command window.

Other useful plotting functions are and text. These functions place text on tile plot. Both .accept text within parentheses and single quotes, as with the xlabel function. The title function places the text at the top of the plot; the function places the text at the point on the plot where the cursor is located when-you click the left mouse button.

You can create multiple plots-called overlay plots by including another set or sets of values in the plot function. For example, to plot the functions y = 2√x and z=4 sin 3x for 0 ≤ x ≤ 5 on the same plot, the session is
»x [0:0.01:5];
»y = 2*sqrt(x);
»z = 4*sin(3*x);
»plot (x,y,x,z), xlabel (‘x’), gtext (‘y’) , gtext (‘z’)

After the plot appears on the screen, the program waits for you to position the cursor and click the mouse button, once for each gt ext function used.

Although MATLAB displays different colors for each curve, if you are going to print the plot on a black-and-white printer, you should label each curve so that you know which curve represents y and which curve represents z. One way of doing this is to use the gtext function to place the labels y and z next to the appropriate curves, as shown in the above session. Another way is to use the legend function, which is discussed.

The plotting functions xlabel, ylabel, title, and gtext’must be placed after the plot function and separated by commas.

You can also distinguish curves from one another by using different line types for each curve. For example, to plot the z curve using a dashed line, replace the plot (x, y, x, z ) function in the above session with plot (x , y, x , z, ‘–‘). Other line types can be used.

In the above example, we had many values in the arrays to be plotted, and thus the curve plotted in Figure 1.3-1 is smooth. When plotting functions, you should always use arrays that have several hundred points so they will plot as continuous curves. This should be done because functions are defined at an infinite number of points. You should never plot a function using data markers or a small number of points.

Sometimes it is useful or necessary to obtain the coordinates of a point on a plotted curve. The function 9 inpu t can be used for this purpose. Place it at the end of all the plot and plot formatting statements, so that the plot will be in its final form. The command [x, y] = ginput (n ) gets n points and returns the r and y coordinates in the vectors x and y, which have a length n. Position the cursor using a mouse, and press the mouse button. The returned coordinates have the same scale as the coordinates on the plot.

In cases where you are plotting data, as opposed to functions, you should use data markers to plot each data point (unless there are very many data points). To mark each point with a plus sign +, the required syntax for the plot function is plot (x, y, z ). You can connect the data points with lines if you wish. In that case, you must plot the data twice, once with a data marker, and once without a marker.

For example, suppose the data for the independent variable is x = [15 : 2 :23] with units of seconds, and the dependent variable values are y = [20, 50, 60, 90, 70] with units of volts. To plot the data with plus signs use the following session: Never forget to label your plots with the units of measurement! Other data markers are available. These are discussed in Chapter 5. Table 1.3-3 summarizes these plotting commands. The gr id command puts grid lines on the plot. We will discuss other plotting functions, and the Plot Editor. The chapter also discusses how to use plots to develop mathematical models from data. This process is called function discovery and regression.

Linear Algebraic Equations

You can use the left division operator (\) in MATLAB to solve sets of linear algebraic equations. For example, consider the set

6x + 12y + 4z = 70
7x – 2y + 3z = 5
2x + 8y – 9z = 64

To solve such sets in MATLAB you must create two arrays; we will call them A and B. The array A has as many rows as there are equations, and as many columns as there are variables. The rows of A must contain the coefficients of x, y, and z in that order. In this example, the first row of A must be 6, 12,4; the second row must be 7, -2, 3, and the third row must be 2, 8, -9. The array B contains the constants on the right-hand side of the equation; it has one column and as many rows as there are equations. In this example, the first row of B is 70, the second is 5, and the third is 64. The solution is obtained by typing A \B. The session is The solution is x = 3, y = 5, and z = -2.

This method works fine when the equation set has a unique solution. To learn how to deal with problems having a nonunique solution (or perhaps no solution at all!).

Statistics

MATLAB has a number of useful functions for performing statistical calculations and other types of data manipulation. For example. you can compute the mean (the average) of a set of values stored in the array x by typing mean (x) . The standard deviation is obtained by typing s t d (x) these topics, as well as methods for obtaining several types of specialized histogram plots used in statistical analysis. The chapter also describes methods for developing simulations based on random number generation and methods for interpolating data.

Numerical Calculus, Differential Equations, and Simulink

Given a set of x and y values, MATLAB can numerically compute the derivative dy / dx and the integral ƒ y d x . In addition, MATLAB can numerically solve differential equations, which are equations involving derivatives; for example,

dy/dx + 5y² = 3sin8x

where the desired solution is y(x) deals with these methods.

Symbolic Processing

Given a function y(»), MATLAB can be used to obtain the derivative dy / dx and the integral ƒ y d x in symbolic form. that is. as a formula instead of as a set of numerical values. This can be done with the Symbolic Math toolbox. In addition, this toolbox can be used to symbolically solve many types of algebraic, transcendental, and differential equations. Chapter 10 covers these methods.

Posted on July 13, 2015 in An Overview of MATLAB

Back to Top
Share This