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

Solving Equations       19


                          sol =
                              x: [2x1 sym]
                              y: [2x1 sym]

                     To see the vectors of x and y values of the solution, type sol.x and sol.y.To
                     see the individual values, type sol.x(1), sol.y(1), etc.
                       Some equations cannot be solved symbolically, and in these cases solve
                     tries to find a numerical answer. For example,


                       >> solve(’sin(x) =2-x’)

                       ans =
                       1.1060601577062719106167372970301

                       Sometimes there is more than one solution, and you may not get what you
                     expected. For example,

                       >> solve(’exp(-x) = sin(x)’)

                       ans =
                       -2.0127756629315111633360706990971
                       +2.7030745115909622139316148044265*i

                     The answer is a complex number; the i at the end of the answer stands for
                                 √
                     the number   −1. Though it is a valid solution of the equation, there are also
                     real number solutions. In fact, the graphs of exp(−x) and sin(x) are shown in
                     Figure 2-3; each intersection of the two curves represents a solution of the
                     equation e −x  = sin(x).
                       You can numerically find the solutions shown on the graph with fzero,
                     which looks for a zero of a given function near a specified value of x. A solution
                     of the equation e −x  = sin(x) is a zero of the function e −x  − sin(x), so to find the
                     solution near x = 0.5 type

                       >> fzero(inline(’exp(-x) - sin(x)’), 0.5)

                       ans =
                              0.5885
                     Replace 0.5 with 3 to find the next solution, and so forth.

                     In the example above, the command inline, which we will discuss further in
                       the section User-Defined Functions below, converts its string argument to a
   33   34   35   36   37   38   39   40   41   42   43