Page 30 - A Guide to MATLAB for Beginners and Experienced Users
P. 30

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((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 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 × 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
   25   26   27   28   29   30   31   32   33   34   35