# Numerical Integration

## Numerical Integration with MATLAB


       
  


This chapter essentially deals with the problem of computing the area under a curve. First, we will employ a basic approach and form trapezoids under a curve. From these trapezoids, we can calculate the total area under a given curve. This method can be tedious and is prone to errors, so in the second half of the chapter, we will utilize a built-in MATLAB function to carry out numerical integration. 
  

### A Basic Approach

There are various methods to calculating the area under a curve, for example,  Rectangle Method,  Trapezoidal Rule and  Simpson's Rule. The following procedure is a simplified method.   
Consider the curve below:


Each segment under the curve can be calculated as follows:
Therefore, if we take the sum of the area of each trapezoid, given the limits, we calculate the total area under a curve. Consider the following example.

### The Trapezoidal Rule

Sometimes it is rather convenient to use a numerical approach to solve a definite integral. The trapezoid rule allows us to approximate a definite integral using trapezoids.


### The trapz Command

Z = trapz(Y) computes an approximation of the integral of Y using the trapezoidal method.

Now, let us see a typical problem.

### The integral Function

As we have seen earlier, trapz gives a good approximation for definite integrals. The integral function streamlines numerical integration even further. Before we learn about integral function, first we will look at anonymous functions. 


### Anonymous Functions

An anonymous function is a function that can be defined in the command window (i.e. it does not need to be stored in a program file). Anonymous functions can accept inputs and return outputs, just as standard functions do such as sqrt(X) or log(X).

To define an anonymous function, first we create a handle with @(x) and type in the function: myfunction=@(x) x^2+1.
If you want to evaluate myfunction at 1, just type in a=myfunction(1) at the command window and you get the result of 2.
Syntax for To evaluate an integral from a minimum to a maximum value, we specify a function and its minimum and maximum Z = integral(fun,xmin,xmax).

### Summary of Key Points

1. In its simplest form, numerical integration involves calculating the areas of segments that make up the area under a curve,
2. MATLAB has built-in functions to perform numerical integration,
3. Z = trapz(Y) computes an approximation of the integral of Y using the trapezoidal method.
4. Anonymous functions are inline statements that we can define with @(x),
5. Z = integral(fun,xmin,xmax) numerically integrates function fun from xmin to xmax.