Using trapz and linspace to evaluate an integral in Matlab

11.7k Views Asked by At

I have two functions f(x) and g(x), and I need to find a numerical approximation to the area bounded by the two curves.

How do I do this using the trapz and linspace functions?

Thanks

1

There are 1 best solutions below

1
On BEST ANSWER

Suppose I want to integrate over $[0 ,2\pi]$, and divide that into $1000$ subintervals.

To do this, first create a vector for the interval:

>>X = linspace(0,2*pi,1000);

Then create a vector containing the function values you want to integrate. If $f(x) = \sin(x)$ and $g(x) = x^2$ then the area between them is equal to the integral of their difference, and I would use

>>Y = sin(X) - X.^2;

finally, integrate

>>my_answer = trapz(X,Y);

Or, if you want it to display the answer, you can omit the semi-colon. e.g.

>>my_answer = trapz(X,Y)

ans = -82.6834

or if you don't even care about storing the value (only displaying it)

>>trapz(X,Y)

ans = -82.6834