Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

http://www2.math.umd.edu/~immortal/206/tutorial/SolvingEquations.

shtml

Solving Equations
Symbolic Solutions vs. Numerical Solutions
We can ask MATLAB to try to solve equations two different ways. MATLAB can sometimes obtain a symbolic solution by manipulating the symbols in the equation(s) much like you would do with pencil and paper in an introductory math class. This approach works well for some problems. Unfortunately there is a large class of problems that will defy attempts to solve them this way. For example try solving (by hand) the equation
ln(x)+x+1=0

It looks easy to solve but it isn't! An equation like this one can be solved using a numerical method which will yield a very good approximation to the precise answer. The numerical approach usually involves taking an initial estimate of the correct solution and then repeating some kind of calculation over and over to gradually improve the estimate.

Solving One Equation Symbolically


Suppose you want to find the solutions to the quadratic equation
x^2-5x=14

Matlab can solve this with the solve command. First we symbolically define our variable x and then apply the command. Try this:
syms x solve ('x^2 - 5 * x = 14') ans = -2 7

That was easy! MATLAB found both of the solutions. You can also ask MATLAB to solve equations that involve arbitrary constants. A nice example is to try to find the general solutions to the generalized form of the quadratic equation ax^2+bx+c=0. What do you think the solutions should look like? Let's see if you're right...
syms x a b c solve('a * x ^ 2 + b * x + c=0') ans = -(b + (b^2 - 4*a*c)^(1/2))/(2*a) -(b - (b^2 - 4*a*c)^(1/2))/(2*a)

Do those solutions look familiar? (You may have to mentally re-arrange them to make them look the way you're used to seeing them!) Important Note 1 How does Matlab know which variable to solve for? It tries to follow common-sense respecting what we usually solve for. Since the variable x is so common it solves for that one first. Suppose we wished to solve ax^2+bx+c=0 for a; we'd have to tell Matlab as follows:
solve('a*x^2+b*x+c=0','a') ans = -(c + b*x)/x^2

Important Note 2 If we're interested in simply having the equation equal to zero we can drop the =0 portion. For example:
solve('2*x+3')

ans = -3/2

Important Note 3 Consider the following:


a=2;b=3; solve('a*x+b') ans = -b/a

Oh dear, what happened? Because of the single quotes around the expression a*x+b Matlab treats this expression symbolically, meaning it treats the letters a and b as letters, not as variables. The values we assigned to them are completely ignored. There are two ways around this, one is to simply drop the single quotes - this forces Matlab to treat the expression not as a string:
solve(a*x+b) ans = -3/2

The other way is to use the subs command which we'll learn later. A warning though, the method above, dropping the single quotes, can only be done if the expression is equal to 0.

Solving a System of Equations Symbolically


You can use the solve command for a whole system of equations as well. For example, suppose we are trying to find the solution to the following system of equations:
3x + 4y + z - 7 = 0 x - y -15 = 0 6x - 2y - 5z + 11 = 0 We can try to use the solve

command to do this by feeding it all of the equations at once, separating them with commas:
syms x y z solve (3 * x + 4 * y + z - 7, x - y - 15, 6 * x - 2 * y - 5 * z + 11) ans = x: [1x1 sym] y: [1x1 sym] z: [1x1 sym]

Hmmmm. That output is a bit disappointing! To enable us to see the actual answers conveniently, we can introduce an intermediate variable that will store the whole "vector" of answers. Then we can view the values individually. Here's how that might look:
syms x y z MyAnswers = solve (3 * x + 4 * y + z - 7, x - y - 15, 6 * x - 2 * y - 5 * z + 11) MyAnswers = x: [1x1 sym] y: [1x1 sym] z: [1x1 sym]

Now we can ask to see each of the three values individually, as follows:
MyAnswers.x

ans = 98/13 MyAnswers.y ans = -97/13 MyAnswers.z ans = 185/13

Another way to accomplish the same thing is by assigning the value of the computation to a vector comprised of variables like this:
[x y z] = solve (3 * x + 4 * y + z - 7, x - y - 15, 6 * x - 2 * y - 5 * z + 11) x = 98/13 y = -97/13 z = 185/13

Notice that the answers are displayed as fractions rather decimal expansions. Does that surprise you? It actually makes sense because Matlab solved the equations symbolically. If you solved these equations by hand, the last operation you would do in calculating z would be to take 185 and divide it by 13. Although you could try to evaluate this as a decimal why should you? The expression 185/33 is exact. If this were written as a decimal it would be 14.230769230769230769230769.... We could only write down an approximation this way and besides -- it looks really hideous! Warning!!! The solve command returns a vector with entries in alphabetical order. For example
solve(x+y,x-y+2)

will return the vector whose first entry is x and whose second entry is y. If you do something like
[y x]=solve(x+y,x-y+2) then what happens is that y gets

assigned to the x solution and x gets assigned to the y solution.

This is not what you want. To unconfuse things make sure that your entries in the vector on the left are in alphabetical order! For example if your variables are dogs and cats then don't do:
[dogs,cats] = ...

instead do
[cats,dogs] = ...

Self-Test

1. We are about to use the variables x and y in some formulas -- declare them as "symbolic". 2. Write a MATLAB command that will find the solutions to the equation x^2 - x = 7. 3. Use MATLAB to find solutions to the system of equations consisting of: 2x + 3y = 60 and -x = 2y + 20

Answers to Self-Test
1. We are about to use the variables x and y in some formulas -- declare them as "symbolic".
syms x y

2. Write a MATLAB command that will find the solutions to the equation x^2 - x = 7.
solve(x^2 - x - 7) ans = 1/2 - 29^(1/2)/2 29^(1/2)/2 + 1/2 3. Use MATLAB to find solutions to the system of equations consisting of: 2x + 3y = 60 and -x = 2y + 20 [x y] = solve(2 * x + 3 * y - 60, x + 2 * y + 20) x = 180 y = -100

Solving Equations Numerically


What are Numerical Methods?
Some equations can't be solved symbolically. For these, we can still ask Matlab to try to find very close approximations using numerical methods. Later, we'll show some more advanced examples, but for now, let's try an easy one. Suppose we want to find the solution to the equation log(x) + x + 1 = 0. (Remember that Matlab uses log for natural log!) We can try to solve this symbolically as shown below:
syms x solve(log(x) + x + 1) ans = 1/(exp(1)*exp(lambertw(0, 1/exp(1))))

Although this answer is ugly, it is 100% exact. [By the way, exp(1) is the constant e=2.7183... The problem with this answer is that unless you are already familiar with the Lambert W (Omega) function, this ugly formula will not be very useful for you. Even if you do know what Lambert's W function is, you still have to do more work to figure out what actual numerical value the above formula represents. Sometimes you just want to see a number, even if it isn't exactly precise!

Solving an Equation Numerically using fzero


Instead of having Matlab solve the equation symbolically, let's try to do it numerically. We'll employ a command fzero which will use some sophisticated numerical techniques to find the zeros of any equation. To use the fzero command we have to first come up with an estimate

of the correct answer. The fzero command will take our estimate and repeatedly apply an algorithm that will obtain a better and better approximation. Let's say our starting estimate is the value 2. We would call fzero like this:
syms x fzero('log(x) + x + 1', 2) ans = 0.2785

If you'd like to learn more about how fzero works and what some of its limitiations are, consult the Matlab helpfile on fzero or wait until a bit later in the tutorial. We'll get more practice with numerical methods later, after we've developed proper notation for representing functions in Matlab.

Self-Test
1. First, use solve to solve the following equation symbolically: sin(x) = 0.5. Note that Matlab finds two solutions! 2. Now try to use fzero to solve this same equation numerically. See if you can find initial estimates that will yield each of the two solutions you found in part 1. 3. Which solutions are more precise, those found symbolically, or those found numerically? 4. Which can be used to solve a wider spectrum of problems: symbolic methods or numerical methods?

Answers to Self-Test
1. First, use "solve" to solve the following equation symbolically: sin(x) = .5. Note that MATLAB finds two solutions!
syms x solve(sin(x) - .5) ans = pi/6 (5*pi)/6

2. Now try to use fzero to solve this same equation numerically. See if you can find "initial estimates" that will yield each of the two solutions you found in part 1.
fzero(@(x) sin(x) - .5, 1) fzero(@(x) sin(x) - .5, 3) ans = 0.5236 ans = 2.6180

3. Which solutions are more precise, those found symbolically, or those found numerically? Typically symbolic solutions are more precise, since they do not involve rounding answers. Numerical solutions are almost always an approximation. 4. Which can be used to solve a wider spectrum of problems: symbolic methods or numerical methods? Numerical solutions can solve problems that are very difficult if not impossible to solve symbolically.

Script M-files
What is a Script M-File?
Before we proceed further consider that when you're writing a Matlab project which involves typing a bunch of commands you probably don't want to type them over and over. In other words it would be helpful to create a "project" which contained all the commands you wished to execute. This would also be convenient for handing in homework assignments (hint hint!) Script M-files allow us to do this. Simpler than the function M-files we'll look at later, script Mfiles are just text files with a .m extension which contain Matlab code that you want to run.

A Simple Script M-File


Suppose you want to write a series of commands to demonstrate your fantastic Matlab knowledge. You wish to put those in a file and then turn it in to your teacher. Simple! First create your first script. The following can be done either from within Matlab (which will open its own editor for you) or with any text editor you prefer.
edit firstscript.m

In this file type the following. This is simply a giant collection of a bunch of commands you've already learned.
3+5 sqrt(10) gcd(120,90) date format long 1/7 format short 1/7 x=3.1 x^2 syms t factor(t^3-5*t^2-6*t) syms a b [a b] = solve(2*a+4*b,a-b) syms x fzero(@(x) exp(x)+x,0)

Save this file. Now the file is available and as long as it is available you can run those lines of code simply by typing the following into Matlab.
firstscript ans = 8 ans = 3.1623 ans = 30 ans = 29-Jan-2011

ans = 0.142857142857143 ans = 0.1429 x = 3.1000 ans = 9.6100 ans = t*(t + 1)*(t - 6) a = 0 b = 0 ans = -0.5671

Note: When you run your script do not add the .m extension! If you do the script will run and then you'll get a peculiar error. Just for the record, script M-files do not take parameters and do not return values. They simply contain lists of commands which are executed sequentially. For this reason they're perfect for doing a homework assignment which will be handed in. Moreover as we'll see in a subsequent lesson, M-files can be published to create html code which contain the commands and all the output (including graphs!) as well as comments. That's coming up shortly!

Self-Test
1. Write a script M-file which does all of the following in order: Calculate 1457*2354, calculate 17!, assign the variable x to the value 7, calculate x^2-x, double the answer to the previous using ans, declare x and y symbolically, factor x^4-5x^2+4, solve y^2+2y10=0 and numerically solve x=cos(x) near x=0.5.

Plotting Curves
A picture is worth 1000 words. Let's learn how to get Matlab to show us some graphs. The easiest way is to use a command called ezplot. Suppose you want to draw the graph of the function f(x)=sin(x) over the interval from -pi to pi. Try typing the following command:
syms x

ezplot(sin(x), [-pi, pi])

After executing the ezplot command, you should see a small window pop up containing a graph that looks like the image above. Wow, that was easy! Try a few more:
ezplot(tan(x), [-pi * 4, pi * 4])

How about this one:


ezplot(sin(1/x), [0, 0.2])

Try some of your own! There is an alternative function called plot that gives you much more flexibility and options with your graphs, but it is a bit more advanced. If you'd like to learn about plot, try reading the Matlab help entry or wait until it turns up later in the tutorial (it does!) Some of it will make more sense after you've learned more about how to use functions in Matlab, which we'll talk about later.

Self-Test
1. Have you ever wondered what the graph of the function f(x) = x * sin(x) looks like? Of course you have. Find out using ezplot. 2. Suppose you want to find the solutions to the equation 5*x^2 - 125*ln(x) = 0. First try to solve this equation symbolically, using solve. How do you like them apples?

3. OK, it looks like you'll probably want to try a numerical method for solving that crazy equation in the previous question. In order to use fzero, you'll need to start with an initial estimate -- but how do you know what value to choose? Use ezplot to draw a graph of this function. Try different ranges until you can see approximately where this graph crosses the x-axis. Now solve the equation with fsolve using the estimated zero obtained visually from the graph.

Answers to Self-Test
1. Have you ever wondered what the graph of the function f(x) = x * sin(x) looks like? Of course you have. Find out using ezplot.
syms x ezplot(x * sin(x))

2. Suppose you want to find the solutions to the equation 5*x^2 - 125*ln(x) = 0. First try to solve this equation symbolically, using "solve". How do you like them apples?
solve(5 * x^2 - 125 * log(x)) ans = 1/exp(wrightOmega(log(2/25) + pi*i)/2)

I have no idea what wrightOmega is, do you? 3. OK, it looks like you'll probably want to try a numerical method for solving that crazy equation in the previous question. In order to use fzero, you'll need to start with an initial estimate -- but how do you know what value to choose? Use ezplot to draw a graph of this function. Try different ranges until you can see approximately where this graph crosses the xaxis. Now solve the equation with fsolve using the estimated "zero" obtained visually from the graph.
ezplot(5 * x^2 - 125 * log(x))

OK, I see that there is a zero someplace near x = 1, so we'll try that as an initial value:
fzero(@(x) 5 * x^2 - 125 * log(x), 1) ans = 1.0446

You might also like