Write a general MATLAB function for integrating experimental data using
Simpson’s 1/3 rule. Your function should check if there are an odd number of
intervals, if there are, the trapezoidal rule should be used for the last interval.
The first line of your MATLAB function should look like:
function I = Simpson(x,y)
Where the function numerically evaluates the integral of the vector of function
values ‘y’ with respect to ‘x’
Your matlab function should also include the following:
• Error check that the inputs are the same length
• Error check that the x input is equally spaced
• Warn the user (not an error, just a warning) if the trapezoidal rule has to
be used on the last interval.
1
Expert's answer
2018-04-11T08:18:02-0400
Solution: function I = Simpson( x, y ) %integrating experimental data using Simpsons 1/3 rule % control lengths of data [m,nX]=size(x); [m,nY]=size(y); if (nX ~= nY) error('input data have different lengths'); end if (nX < 2) error('input data of insufficient length'); end % control of the length of intervals between points h = x(2) - x(1); for i=3:nX if (x(i)-x(i-1)) ~= h error('x input is not equally spaced'); end end % Simpson 1/3 rule sum = y(1); for i=2:(nX-2) if mod(i,2)==0 sum=sum+4*y(i); else sum=sum+2*y(i); end end % last interval if mod(nX,2) == 0 disp('warning: the trapezoidal rule has to be used on the last interval'); sum = sum + y(nX-1); I = (sum*h/3) + ((y(nX) + y(nX-1))*h/2); else sum = sum + 4*y(nX-1) + y(nX); I=sum*h/3; end disp('Integral='); disp(I); end
Comments
Leave a comment