We now show how to start MATLAB, how to make some basic calculations, and how to exit MATLAB.
In this text we use typewriter font to represent MATLAB commands, any text that you type in the computer, and any MATLAB responses that appear on the screen, for example, y = 6*x. Variables in normal mathematics text appear in italics; for example, y = 6x. We use boldface type for three purposes: to represent vectors and matrices in normal mathematics text (for example, Ax = b), to represent a key on the keyboard (for example, Enter), and to represent the name of a screen menu or an item that appears in such a menu (for example, File). It is assumed that you press the Enter key after you type a command. We do not show this action with a separate symbol.
To start MATLAB on aMS Windows system, double-click on the MATLAB icon. You will then see the MATLAB Desktop. The Desktop manages the Command window and a Help Browser, as well as other tools. The default appearance of the Desktop is shown in Figure 1.1-1. Three windows appear. These are the
Command window, the Command History window, and the Current Directory window. Across the top of the Desktop are a row of menu names, and a row of icons called the too/bar. To the right of the toolbar is a box showing the directory where MATLAB looks for and saves files. We will describe the menus, toolbar, and directories later.
You’ use the Command window to communicate with the MATLAB program, by typing instructions of various types called commands, functions, and statements. Later we will discuss the differences between these types, but for now, to simplify the discussion, we.will call the instructions by the generic name commands. MATLAB displays the prompt (») to indicate that it is ready to receive instructions. Before giving MATLAB instructions, make sure the cursor is located just after the prompt. If it is not, use the mouse to move the cursor. The prompt in the Student Edition looks like EDU». We will use the normal prompt symbol» to illustrate commands in this text.
Three other windows appear in the default Desktop. The Current Directory window is much like a file manager window; you can use it to access files. Double-clicking on a file name with the extension .m will open that file in the MATLAB Editor. The Editor is discussed in Section 1.4.
Underneath the Current Directory window is the Workspace window. To activate it, click on its tab at the bottom of the Current Directory window. The Workspace window displays the variables created in the Command window. Double-click on a variable name to open the Array Editor, which is discussed.
The fourth window in the default Desktop is the Command History window. This window shows all the previous keystrokes you entered in the Command window. It is useful for keeping track of what you typed. You can click on a keystroke and drag it to the Command window or the Editor. Double-clicking on a keystroke executes it in the Command window.
You can alter the appearance of the Desktop if you wish. For example, to eliminate a window, just click on its Close-window button (x) in its upper right-hand corner. To undock, or separate the window from the Desktop click on the button containing an arrow. You .can manipulate other windows in the same way. To restore the default configuration, click on the View menu, then click on Desktop Layout, and select Default.
Entering Commands and Expressions
To see how simple it is to use MATLAB, try entering a few commands on your computer. If you make a typing mistake, just press the Enter key until you get the prompt, and then retype the line. Or, because MATLAB retains your previous keystrokes in a command file, you can use the up-arrow key (↑) to scroll back through the commands. Press the key once to see the previous entry, twice to see the entry before that, and so on. Use the down-arrow key (↓) to scroll forward through the commands. When you find the line you want, you can edit it using the left- and right-arrow keys (← and →), and the Backspace key, and the Delete key. Press the Enter key to execute the command. This technique enables you to correct typing mistakes quickly.
Note that you can see your previous keystrokes displayed in the Command History window. You can copy a line from this window to the Command window by highlighting the line with the mouse, holding down the left mouse button, and dragging the line to the Command window.
Make sure the cursor is at the prompt in the Command window. To divide 8 by 10, type 8/10 and press Enter (the symbol/is the MATLAB symbol for division). Your entry and the MATLAB response looks like the following on the screen (we call this interaction between you and MATLAB an interactive session, or simply a session).
MATLAB uses high precision for its computations, but by default it usually displays its results using four decimal places. This is called the short format This default can be changed by using the format command. which is discussed later in this section. MATLAB uses the notation e to represent exponentiation to a power of 10; for example, MATLAB displays the number 5.316 x 10² as 5.316e+02.
MATLAB has assigned the answer to a van able called ans. which is an abbreviation for answer. A variable in MATLAB is a symbol used to contain a value. You-can use the variable ans for further calculations: for example, Using the MATLAB symbol for multiplication (*):
» 5* ans
Note that the variable ans now has the value 4.
You can use variables to write mathematical expressions. We will soon see why this is all’ advantage. You can assign the result to a variable of your own choosing, say r, as follows:
Spaces in’the line improve its readability; for example, you can put a space before and after the = sign if you want. MATLAB ignores these spaces when making its calculations.
If you now type r at the prompt, you will see
thus verifying that the variable r has the value 0.8. You can use this variable in further calculations. For example,
» s = 20*r
When we do not specify a variable name’ for a result, MATLAB uses the symbol ans as a temporary variable containing the most recent answer.
MATLAB has hundreds of functions available. One of these is the square root function, sqrt. A pair of parentheses is used after the function’s name to enclose the value-called the function’s argument that is operated on by the function. For example, to compute the square root of 9, you type sqrt (9). We will see more MATLAB functions; an extensive list of mathematical functions is given. Other types of functions are covered through out the text.
Order of Precedence
A scalar is a single number. A scalar variable is a variable that contains a single number. MATLAB uses the symbols + – * / ∧for addition, subtraction, multiplication, division, and exponentiation (power) of scalars. These are listed in Table 1.1-1. Fill example, typing x = 8 + 3 * 5 returns the answer x = 23.
Typing 2∧ 3 -10 returns the answer an s = -2. The forward slash (!) represents right division, which is the normal division operator familiar to you. Typing 15/ 3 returns the result ans = 5.
MATLAB has another division operator, called left division, which is denoted by the backslash (\). The left division operator is useful for solving sets of linear algebraic equations, as we will see in Section 1.3. A good way to remember the difference between the right and left division operators is to note that the slash slants toward the denominator. For example, 7/2 = 2\ 7 = 3.5.
The mathematical operations represented by the symbols + – * / \, and ∧ follow a set of rules called precedence. Mathematical expressions are evaluated PRECEDENCE starting from the left, with the exponentiation operation having the highest order of precedence, followed by multiplication and division with equal precedence, followed by addition and subtraction with equal precedence. Parentheses can be
Table 1.1-2 Order of precedence
First Parentheses. evaluated starting with the innermost pair.
Second Exponentiation evaluated from left to right.
Third Multiplication and division with equal precedence evaluated from left to right
Fourth Addition and subtraction with equal precedence evaluated from left to right.
used to alter this order. Evaluation begins with the innermost pair of parentheses, and proceeds outward. Table 1.1-2 summarizes these rules. For example, note the effect of precedence on the following session.
» 8 + 3 * 5
» 8 + ( 3 * 5 )
» ( 8 + 3 ) * 5
» 4 ∧ 2 – 12 – 8 / 4 * 2
» 4 ∧ 2 – 12 – 8 / ( 4 * 2)
» 3 * 4 ∧ 2 + 5
»( 3 * 4 ) ∧ 2 + 5
»27 ∧ ( 1/3 ) + 32 ∧ ( 0.2 )
» 27 ∧ ( 1 / 3 ) + 32 ∧ 0.2
» 27 ∧ 1/3 + 32 ∧ 0.2
To avoid mistakes, you should feel free to insert parentheses wherever you are unsure”of the effect precedence will have on the calculation. Use of parentheses also improves the readability of your MATLAB expressions. For example, parentheses are not needed in the expression 8 + ( 3 * 5 ) ; but they make clear our intention to multiply 3 by 5 before adding 8 to the result.
The Assignment Operator
The = sign in MATLAB is the called the assignment or replacement operator. Itworks differently than the equals sign you know from mathematics. When youtype x=3, you tell MATLAB to assign the value’ 3 to the variable x. This usageis no different than in mathematics. However, in MATLAB we can also typesomething like this: x = x + 2. This tells MATLAB to add 2 to the currentvalue of x, and to replace the current value of x with this-new value. If x originally had the value 3, its new value would be 5. This usage of the = operator is different from its use in mathematics. For example, the mathematics equation x =x .+ 2 is invalid because it implies that 0 = 2 (subtract x from both sides of the equation to see this).
It is important to understand this difference between the MATLAB operator = and the equals sign of mathematics. The variable on the left-hand side of the = operator is replaced by the value generated by the right-hand side. There- , fore, one variable, and only one variable, must be on the left-hand side of the = operator. Thus in MATLAB you cannot type 6 = x. Another consequence of this restriction is that you cannot write in MATLAB expressions like the following:
The corresponding equation x + 2 = 20 is acceptable in algebra, and has the solution x = 18, but MATLAB cannot solve such an equation without additional commands (these commands are available in the Symbolic Math toolbox, which is described ).
Another restriction is that the right-hand side of the = operator must have a computable value. For example, if the variable y has not been assigned a value, then the following will generate an error message in MATLAB.
»x = 5 + Y
In addition to assigning known values to variables, the assignment operator is very useful for assigning values that are not known ahead of time, or for changing the value of a variable by using a prescribed procedure. The following example shows how this is done.
The term workspace refers to the names and values of any variables in use in the current work session. Variable names must begin with a letter and must contain Ie than 32 characters; the rest of the name can contain letters, digits, and underscore characters. MATLAB is case-sensitive. Thus the following names represent five different variables: speed, Speed, SPEED,Speed_I, and Speed_2.
Managing the Work Session
Table 1.1-3 summarizes some commands and special symbols for managing the work session. A semicolon at the end of a line suppresses printing the result to the screen. If. a semicolon is not put at the end of a line, MATLAB display the results of the line on the screen. Even if you suppress the display with the semicolon, MATLAB still retains the variable’s value.
You can put several commands on the same line if you separate them with comma-if you want to see the results of the previous command-or semicolon
if you want to suppress the display. For example,
Use the arrow.tab, and control keys to recall, edit, and reuse functions and variables you typed earlier. For example, suppose you mistakenly enter the-line
»volume = 1 + sqr(5)
MATLA:B responds with the error message
Undefined Function or variable ‘sqr’.
because you misspelled sqrt. Instead of retyping the entire line, press the up arrow key (↑) once to display the previously typed line, Press the left-arrow key (←) several times to move the cursor and add the missing t, then press Enter.
Repeated use of the up-arrow key recalls lines typed earlier.
You can use the smart recall feature to recall a previously typed function or variable whose first few characters you specify. For example, after you have entered the line starting with volume,typing vol and pressing the up-arrow key (↑) once recalls the last-typed line that starts with the function or variable whose name begins with vol. This feature is case-sensitive.
You can use the tab completion feature to reduce the amount of typing. MATLAB automatically completes the name of a function, variable, or file if you type the first few letters of the name and press the Tab key. If the name is unique, it is automatically completed. For example, in the session listed earlier, if you type Fruit and press Tab, MATLAB completes the name and displays Fruit Purchased. Press Enter to display the value of the variable, or continue editing to create a new executable line that uses the variable Fruit Purchased.
If there is more than one name that starts with the letters you typed,
MATLAB displays nothing. In this case press the Tab key again to see a list of the possibilities. The up-arrow (↑) and down-arrow (↓) keys move up and down through the previously typed lines one line at a time. Similarly, the left-arrow. (←) and rightarrow (→) keys move left and right through a line one character at a time.
To move through one word at a time, press Ctrl and simultaneously to move to the right; press Ctrl and simultaneously to move to the left. Press Home to move to the beginning of a line; press End to move to the end of a line. Press Del to delete the character at the cursor; press Backspace to delete the character before the cursor. Press Esc to clear the entire line; press Ctrl and k simultaneously to delete (kill) to the end of the line.
MATLAB retains the last value of a variable until you quit MATLAB or clear its value. Overlooking this fact commonly causes errors in MATLAB. For example, you might prefer to use the variable x in a number of different calculations. If you forget to enter the correct value for x, MATLAB uses the last value, and you get an incorrect result. You can use the clear function to remove the values of all variables from memory, or you can use the form clear var1 var2. to
clear the variables named var1 and var2. The effect of the clc command is different; it clears the Command window’ of everything in the window display, but the values of the variables remain.
You can type the name of a variable and press Enter to see its current value. If the variable does not have a value (i.e., if it does not exist), you see an error message. You can also use the exist function. Type exist (‘x’), to see if the variable x is in use: If a 1 is returned, the variable exists; a 0 indicates that it does not exist. The who function lists the names of all the variables in memory, but does not give their values. The form who var1 var2 restricts the display to the variables specified. The wildcard character * can be used to / display variables that match a pattern. For instance, who A* finds all variables in the current workspace that start with A. The whos function lists the variable names and their sizes, and indicates whether or not they have nonzero imaginary parts.
The difference between a function and a command or a statement is that functions have their arguments enclosed in parentheses. Commands, such as clear need not have arguments, but if they do, they are not enclosed in parentheses; for example, clear x.Statements cannot have arguments; for example, clc and qui t are statements.
You can quit MATLAB by typing quit. On MS Windows systems you can also click on the File menu, and then click on Exit MATLAB.
MATLAB has several predefined special constants, such as the built-in constant pi we used in Example 1.1-1. Table l.1-4lists them. The symbol Inf stands for 00, which in practice means a number so large that MATLAB cannot represent it. For example, typing 5/0 generates the answer Inf. The symbol NaN stands for “not a number.” It indicates an undefined numerical result such as that obtained by typing 0/0. The symbol eps is the smallest number which, when added to 1 by the computer, creates a number greater than 1. We use it as an indicator of the accuracy of computations.
The symbols i and j denote the imaginary unit, where i = j =√-1 We
use them to create and represent complex numbers, such as x = 5 + 8 i.
Try not to use the names of special constants as variable names. Although MATLAB allows you to assign a different value to these constants, it is not good practice to do so.
Complex Number Operations
MATLAB handles complex number algebra automatically. For example, the number C1 = I – 2i is entered as follows: c 1 = 1-2i.
Caution: Note that an asterisk is not needed between i or j and a number, although it is required with a variable such as c2 = 5 . This convention can cause errors if you are not careful. For example, the expressions y = 7/2 *i and x 7/2 i give two different results: y = (7/2); = 3.5; and x = 7/(2i) = -3.5;
Addition, subtraction, multiplication, and division of complex numbers easily done. For example,
Complex conjugates have the same real part but imaginary parts of opposite sign: for example, -3 +7i and -3 -7i are complex conjugates. The product of tv. conjugates is the sum of the squares of the real and imaginary parts; for example.
» ( -3 + 7i) * ( -3 – 7i )
because √3²+7² =58. More complex number functions are discussed.
The format command controls how numbers appear on the screen. Table 1.1 gives the variants of this command. MATLAB uses many significant figures in i
calculations, but we rarely need to see all of them. The default MATLAB display format is the short format, which uses four decimal digits. You can display more by typing format long, which gives 16 digits. To return to the default mode, type format short.
You can force the output to be in scientific notation by typing format short e, or format long e, where e stands for the number 10.Thus the output 6. 3792e+03 stands for the number 6.3792 x 103. The output 6 . 3792 e – 0 3 stands for the number 6.3792 x 10-3 Note that in this context does not represent the number e, which is the base of the natural logarithm. Here stands for “exponent.” It is a poor choice of notation, but MATLAB follows conventional computer programming standards that were established many years ago.
Use format bank only for monetary calculations; it does-not recognize imaginary parts.