Physics 15a PSI MATLAB Tutorial #3: Numerical Integration: DX 0.5 X (0:dx:2)
Physics 15a PSI MATLAB Tutorial #3: Numerical Integration: DX 0.5 X (0:dx:2)
Matlab cannot solve integrals symbolically (other programs like Mathematica can do this), but it can solve integrals numerically. To understand how Matlab does this, think back to the definition of an integral you learned in calculus: ( ) ( )
An integral can be approximated by a series of boxes drawn under the curve (see figure below); as the number of boxes increases, the approximation gets better and better. This is how Matlab can calculate integrals - it calculates the area of a large number of these boxes and sums them up.
Image credit: http://hyperphysics.phy-astr.gsu.edu/hbase/integ.html For the example shown in the figure, the integral ( ) would look like this in Matlab:
%First set the limits of integration and the step size: dx=0.5; %for N=4 x=[0:dx:2]; %this defines a vector of x values ranging from 0 to 2 in steps of 0.5. You could also use x=linspace[0:2:N], and define N=4. %Define the function: f=7*x-8.5*x.^2+3*x.^3; %Calculate the area under the curve: area=sum(f.*dx)
Enter the code as shown above and see if you get the same values as those shown in the figure for various values of dx.