MATH/CMSC 206 - Introduction to Matlab

Announcements Syllabus Tutorial Projects Submitting

Numerical Integration

Contents

Intro to Numerical Integration

We've seen how the int command can be used to find definite integrals. You should know that int does its job using symbolic integration techniques, similar to the ones you would use if you were integrating something with paper and pencil in a first semester calculus course. Unfortunately, there are many functions that are difficult or impossible to integrate this way. For example, I tried the following:

int(sqrt(sin(x) * 5), 1, 2)
 
ans =
 
(-2)*5^(1/2)*(ellipticE(pi/4 - 1, 2) - ellipticE(1/4*pi - 1/2, 2))
 

That answer is not really what I was after -- I just wanted a number! What in the world is ellipticE anyway?!

Using quad

To handle this definite integral, it might be better to ask Matlab to use a numerical method to compute the answer. There are a few different commands that are built-in to Matlab for handling this task. One of them is called quad which is short for quadrature -- a word that actually means approximate the definite integral using a numerical method. (For now don't worry about the actual method used, just remember that it's like the ones you know - Simpson's Rule and so on.) Here is quad in action:

quad( @(x) sqrt(sin(x) .* 5), 1, 2)
ans =

    2.1863

There are two things that should concern you here. First that @(x) symbol. We'll explain this in more detail later but basically the first argument of quad must be a something called a function handle and the way to make a function into a function handle is to put an @(x) (or whatever variable you're using) in front.

The second issue is that .* that replaced the *. The reason for this is that quad actually does its job in the background using vectors. If you recall from an earlier part of the tutorial the .* command is like multiplication but with vectors. We don't particularly need to care what Matlab is doing in the background with the quad function but we need to make sure we give it the correct format.

So basically just remember to put @(x) in front and in place of *, / and ^ use .*, ./ and .^ and you'll be fine.

Self-Test

  1. Try using int to symbolically calculate the definite integral of the function f(x) = sqrt(x + ln(x)) over the interval [10, 20]. It may take a while. After all that waiting, when you finally see the answer you will be very disappointed! That was useless. Now try it using quad.
  2. Try to find the definite integral of the function f(x) = 2^sin(x) over the interval [1, 2] using both symbolic and numerical methods. Hint: To get this function to work properly with quad, you'll have to use the symbol .^ instead of ^ for exponentiation. Later, you'll learn why!

Answers to Self-Test

Next Topic: Solving Differential Equations