10 Chapter 2:MATLAB Basics >>v=sin(10) v -0.5440 >>u^2+v^2 ans 1 MATLAB uses double-precision floating point arithmetic,which is accurate to approximately 15 digits;however,MATLAB displays only 5 digits by default. To display more digits,type format long.Then all subsequent numerical output will have 15 digits displayed.Type format short to return to 5-digit display. MATLAB differs from a calculator in that it can do exact arithmetic.For example,it can add the fractions 1/2 and 1/3 symbolically to obtain the correct fraction 5/6.We discuss how to do this in the section Symbolic Expressions, Variable Precision,and Exact Arithmetic on the next page. Algebra Using MATLAB's Symbolic Math Toolbox,you can carry out algebraic or symbolic calculations such as factoring polynomials or solving algebraic equations.Type help symbolic to make sure that the Symbolic Math Tool- box is installed on your system. To perform symbolic computations,you must use syms to declare the vari- ables you plan to use to be symbolic variables.Consider the following series of commands: >syms x y >>(x-Y)*(x-y)^2 ans (x-y)^3 >expand(ans)
10 Chapter 2: MATLAB Basics >> v = sin(10) v = -0.5440 >> uˆ2 + vˆ2 ans = 1 MATLAB uses double-precision floating point arithmetic, which is accurate to approximately 15 digits; however, MATLAB displays only 5 digits by default. To display more digits, type format long. Then all subsequent numerical output will have 15 digits displayed. Type format short to return to 5-digit display. MATLAB differs from a calculator in that it can do exact arithmetic. For example, it can add the fractions 1/2 and 1/3 symbolically to obtain the correct fraction 5/6. We discuss how to do this in the section Symbolic Expressions, Variable Precision, and Exact Arithmetic on the next page. Algebra Using MATLAB’s Symbolic MathToolbox, you can carry out algebraic or symbolic calculations suchas factoring polynomials or solving algebraic equations. Type help symbolic to make sure that the Symbolic Math Toolbox is installed on your system. To perform symbolic computations, you must use syms to declare the variables you plan to use to be symbolic variables. Consider the following series of commands: >> syms x y >> (x - y)*(x - y)ˆ2 ans = (x-y)^3 >> expand(ans)
Algebra 11 ans X^3-3*x^2*y+3*X*y^2-y^3 >factor(ans) ans (x-y)^3 √ Notice that symbolic output is left-justified,while numeric output is indented.This feature is often useful in distinguishing symbolic output from numerical output. Although MATLAB makes minor simplifications to the expressions you type,it does not make major changes unless you tell it to.The command ex- pand told MATLAB to multiply out the expression,and factor forced MAT- LAB to restore it to factored form. MATLAB has a command called simplify,which you can sometimes use to express a formula as simply as possible.For example, >simplify((x3 -y3)/(x -y)) ans x^2+x*y+y^2 MATLAB has a more robust command,called simple,that sometimes does a better job than simplify.Try both commands on the trigonometric expression sin (x)*cos (y)+cos (x)*sin(y)to compare-you'll have to read the online help for simple to completely understand the answer. Symbolic Expressions,Variable Precision,and Exact Arithmetic As we have noted,MATLAB uses floating point arithmetic for its calculations. Using the Symbolic Math Toolbox,you can also do exact arithmetic with sym- bolic expressions.Consider the following example: >cos(pi/2) ans 6.1232e-17 The answer is written in floating point format and means 6.1232 x 10-17 However,we know that cos(/2)is really equal to 0.The inaccuracy is due to the fact that typing pi in MATLAB gives an approximation to z accurate
Algebra 11 ans = x^3-3*x^2*y+3*x*y^2-y^3 >> factor(ans) ans = (x-y)^3 ✓ Notice that symbolic output is left-justified, while numeric output is indented. This feature is often useful in distinguishing symbolic output from numerical output. Although MATLAB makes minor simplifications to the expressions you type, it does not make major changes unless you tell it to. The command expand told MATLAB to multiply out the expression, and factor forced MATLAB to restore it to factored form. MATLAB has a command called simplify, which you can sometimes use to express a formula as simply as possible. For example, >> simplify((xˆ3 - yˆ3)/(x - y)) ans = x^2+x*y+y^2 ✓ MATLAB has a more robust command, called simple, that sometimes does a better job than simplify. Try bothcommands on the trigonometric expression sin(x)*cos(y) + cos(x)*sin(y) to compare — you’ll have to read the online help for simple to completely understand the answer. Symbolic Expressions, Variable Precision, and Exact Arithmetic As we have noted, MATLAB uses floating point arithmetic for its calculations. Using the Symbolic Math Toolbox, you can also do exact arithmetic with symbolic expressions. Consider the following example: >> cos(pi/2) ans = 6.1232e-17 The answer is written in floating point format and means 6.1232 × 10−17. However, we know that cos(π/2) is really equal to 0. The inaccuracy is due to the fact that typing pi in MATLAB gives an approximation to π accurate
12 Chapter 2:MATLAB Basics to about 15 digits,not its exact value.To compute an exact answer,instead of an approximate answer,we must create an exact symbolic representation of /2 by typing sym('pi/2').Now let's take the cosine of the symbolic representation ofπ/2: >cos (sym('pi/2')) ans 0 This is the expected answer. The quotes around pi/2 in sym('pi/2')create a string consisting of the characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating point number.The command sym converts the string to a symbolic expression. The commands sym and syms are closely related.In fact,syms x is equiv- alent to x sym('x').The command syms has a lasting effect on its argu- ment(it declares it to be symbolic from now on),while sym has only a tempo- rary effect unless you assign the output to a variable,as in x sym('x'). Here is how to add 1/2 and 1/3 symbolically: >>sym('1/2')+aym('1/3') ans 5/6 Finally,you can also do variable-precision arithmetic with vpa.For example, to print50 digits of√2,type >>vpa('sqrt(2)',50) ans 1.4142135623730950488016887242096980785696718753769 You should be wary of using sym or vpa on an expression that MATLAB must evaluate before applying variable-precision arithmetic.To illustrate,enter the expressions 345,vpa(345), and vpa('345').The first gives a floating point approximation to the answer,the second-because MATLAB only carries 16-digit precision in its floating point evaluation of the exponentiation- gives an answer that is correct only in its first 16 digits,and the third gives the exact answer. See the section Symbolic and Floating Point Numbers in Chapter 4 for details about how MATLAB converts between symbolic and floating point numbers
12 Chapter 2: MATLAB Basics to about 15 digits, not its exact value. To compute an exact answer, instead of an approximate answer, we must create an exact symbolic representation of π/2 by typing sym(’pi/2’). Now let’s take the cosine of the symbolic representation of π/2: >> cos(sym(’pi/2’)) ans = 0 This is the expected answer. The quotes around pi/2 in sym(’pi/2’) create a string consisting of the characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating point number. The command sym converts the string to a symbolic expression. The commands sym and syms are closely related. In fact, syms x is equivalent to x = sym(’x’). The command syms has a lasting effect on its argument (it declares it to be symbolic from now on), while sym has only a temporary effect unless you assign the output to a variable, as in x = sym(’x’). Here is how to add 1/2 and 1/3 symbolically: >> sym(’1/2’) + sym(’1/3’) ans = 5/6 Finally, you can also do variable-precision arithmetic with vpa. For example, to print 50 digits of √ 2, type >> vpa(’sqrt(2)’, 50) ans = 1.4142135623730950488016887242096980785696718753769 ➱ You should be wary of using sym or vpa on an expression that MATLAB must evaluate before applying variable-precision arithmetic. To illustrate, enter the expressions 3ˆ45, vpa(3ˆ45), and vpa(’3ˆ45’). The first gives a floating point approximation to the answer, the second — because MATLAB only carries 16-digit precision in its floating point evaluation of the exponentiation — gives an answer that is correct only in its first 16 digits, and the third gives the exact answer. ☞ See the section Symbolic and Floating Point Numbers in Chapter 4 for details about how MATLABconverts between symbolic and floating point numbers
Managing Variables 13 Managing Variables We have now encountered three different classes of MATLAB data:floating point numbers,strings,and symbolic expressions.In a long MATLAB session it may be hard to remember the names and classes of all the variables you have defined.You can type whos to see a summary of the names and types of your currently defined variables.Here's the output of whos for the MATLAB session displayed in this chapter: >whos Name Size Bytes Class ans 1X1 226 sym object u 1X1 6 double array v 1X1 8 double array x 1x1 126 sym object y 1x1 126 sym object Grand total is 58 elements using 494 bytes We see that there are currently five assigned variables in our MATLAB session.Three are of class "sym object";that is,they are symbolic objects.The variables x and y are symbolic because we declared them to be so using syms, and ans is symbolic because it is the output of the last command we executed, which involved a symbolic expression.The other two variables,u and v,are of class "double array".That means that they are arrays of double-precision numbers;in this case the arrays are of size 1 x 1(that is,scalars).The "Bytes" column shows how much computer memory is allocated to each variable Try assigning u pi,v ='pi',and w sym('pi'),and then type whos to see how the different data types are described. The command whos shows information about all defined variables,but it does not show the values of the variables.To see the value of a variable,simply type the name of the variable and press ENTER or RETURN. MATLAB commands expect particular classes of data as input,and it is important to know what class ofdata is expected by a given command;the help text for a command usually indicates the class or classes ofinput it expects.The wrong class of input usually produces an error message or unexpected output. For example,type sin('pi')to see how unexpected output can result from supplying a string to a function that isn't designed to accept strings. To clear all defined variables,type clear or clear all.You can also type, for example,clear x y to clear only x and y. You should generally clear variables before starting a new calculation. Otherwise values from a previous calculation can creep into the new
Managing Variables 13 Managing Variables We have now encountered three different classes of MATLAB data: floating point numbers, strings, and symbolic expressions. In a long MATLAB session it may be hard to remember the names and classes of all the variables you have defined. You can type whos to see a summary of the names and types of your currently defined variables. Here’s the output of whos for the MATLAB session displayed in this chapter: >> whos Name Size Bytes Class ans 1 x 1 226 sym object u 1 x 1 8 double array v 1 x 1 8 double array x 1 x 1 126 sym object y 1 x 1 126 sym object Grand total is 58 elements using 494 bytes We see that there are currently five assigned variables in our MATLAB session. Three are of class “sym object”; that is, they are symbolic objects. The variables x and y are symbolic because we declared them to be so using syms, and ans is symbolic because it is the output of the last command we executed, which involved a symbolic expression. The other two variables, u and v, are of class “double array”. That means that they are arrays of double-precision numbers; in this case the arrays are of size 1 × 1 (that is, scalars). The “Bytes” column shows how much computer memory is allocated to each variable. Try assigning u = pi, v = ’pi’, and w = sym(’pi’), and then type whos to see how the different data types are described. The command whos shows information about all defined variables, but it does not show the values of the variables. To see the value of a variable, simply type the name of the variable and press ENTER or RETURN. MATLAB commands expect particular classes of data as input, and it is important to know what class of data is expected by a given command; the help text for a command usually indicates the class or classes of input it expects. The wrong class of input usually produces an error message or unexpected output. For example, type sin(’pi’) to see how unexpected output can result from supplying a string to a function that isn’t designed to accept strings. To clear all defined variables, type clear or clear all. You can also type, for example, clear x y to clear only x and y. You should generally clear variables before starting a new calculation. Otherwise values from a previous calculation can creep into the new
14 Chapter 2:MATLAB Basics -MATLAB 日回☒ File Edt Yiow Web Wndow Help x c子日明用8k巨山 Clans >%m('1/2*1+m'1/3) 1x1 226 ymc电ect 11 double array 1x1 do地le arra的 5/6 回x 1x1 126 aym object 回1 >pa('qtt(2,01 1x1 126 aync地j0ct Launch Pad Workspace 1.414213562373095048801668724209 Command Haloy expand (ans) Wase g10 Bytes tactor [ans) 1p11fyg*3-y3)/(x·7)) ans lxl 226 ce8(的1/2) co3(am('p1/2'1】 m('1/2)+8m'1/3') 1×1 126 Ta('a4平t(21',50] h03 command History Curent Directory Ready Figure 2-2:Desktop with the Workspace Browser. calculation by accident.Finally,we observe that the Workspace browser pre- sents a graphical alternative to whos.You can activate it by clicking on the Workspace tab,by typing workspace at the command prompt,or through the View item on the menu bar.Figure 2-2 depicts a Desktop in which the Command Window and the Workspace browser contain the same information as displayed above. Errors in Input If you make an error in an input line,MATLAB will beep and print an error message.For example,here's what happens when you try to evaluate 3u2: >>3u^2 ???3u^2 Error:Missing operator,comma,or semicolon. The error is a missing multiplication operator *The correct input would be 3*u2.Note that MATLAB places a marker (a vertical line segment)at the place where it thinks the error might be;however,the actual error may have occurred earlier or later in the expression
14 Chapter 2: MATLAB Basics Figure 2-2: Desktop with the Workspace Browser. calculation by accident. Finally, we observe that the Workspace browser presents a graphical alternative to whos. You can activate it by clicking on the Workspace tab, by typing workspace at the command prompt, or through the View item on the menu bar. Figure 2-2 depicts a Desktop in which the Command Window and the Workspace browser contain the same information as displayed above. Errors in Input If you make an error in an input line, MATLAB will beep and print an error message. For example, here’s what happens when you try to evaluate 3uˆ2: >> 3uˆ2 ??? 3u^2 | Error: Missing operator, comma, or semicolon. The error is a missing multiplication operator *. The correct input would be 3*uˆ2. Note that MATLAB places a marker (a vertical line segment) at the place where it thinks the error might be; however, the actual error may have occurred earlier or later in the expression