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

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

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

new to matlab and your code is clear and concise. thank you so much!
sorry but why is it trapz(y,x) and not trapz(x,y) ?
My pleasure!
The argument reversal in the trapz call is an oversight error on my part. I started out by doing numerical integration using the integral function (that has the function first and the limits second), then re-read your post and realised you wanted to use trapz.
It should be:
inty = trapz(x(ixrng), yx(ixrng)); % Integral
and the value of the integral is about 0.76. Nothing else in my code needs to change.

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!