How to find area between curve and x-axis using trapz function?

6 views (last 30 days)
x=0.6:0.01:1.8
y=sqrt((x.^2)-(sin(x.^4)))
plot(x,y)
How do I use the trapz function to find the area between y(x) and x-axis BETWEEN THE 2 LOCAL MINIMA of the curve?

Accepted Answer

Star Strider
Star Strider on 27 Oct 2014
I had some fun with this:
x=0.6:0.01:1.8;
y= @(x) sqrt((x.^2)-(sin(x.^4))); % Anonymous Function
yx = y(x); % y(x)
dy = gradient(yx,x); % dy/dx
d2y = gradient(dy,x); % d^2y/dx^2
cs = dy.*circshift(dy,[0 -1]); % Create Zero Crossings
xtr = find((cs <= 0) & (d2y > 0)); % Detect Curve Minima
ixrng = (xtr(1):xtr(2)); % X-Index Range Between Curve Minima
inty = trapz(yx(ixrng), x(ixrng)); % Integral
figure(1)
plot(x,yx)
hold on
patch([x(ixrng) x(flip(ixrng))], [yx(ixrng) zeros(size(ixrng))], [0.1 0.5 0.9])
hold off
grid
text(x(xtr(1))+0.25, yx(xtr(2))-0.5, sprintf('Integral = %8.5f',inty))
Plotting:
The calculus is straightforward, using the first derivative to find the extrema and the second derivative to determine minima. The ‘cs’ assignment creates zero-crossings, the ‘xtr’ assignment uses the first and second derivatives to detect the indices of the minima, and the rest is self-explanatory. The plot is just to demonstrate that the code does what it’s supposed to.
  5 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!