Matlab integral not giving right result as trapz function

I have the following code
x = 0:0.1:1;
y = x.*x;
dy = gradient(y);
dx = gradient(x);
dx_fun = @(z) spline(x,dx,z);
dy_fun = @(z) spline(x,dy,z);
integral(dy_fun,0,1)
trapz(dy_fun(x))
the result obtained by the integral function does not match the result obtained by trapz function. Both bounds of the intergation are the same for both function. Value of trapz(dy_fun(x)) = y(end,1)

 Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 4 Jun. 2020
Bearbeitet: Ameer Hamza am 4 Jun. 2020
Try this
integral(dy_fun,0,1)
trapz(dy_fun(x).*dx) % <== multiply the function value with dx

4 Kommentare

Thanks for your reply. I modified the code as
x = 0:0.1:1;
y = x.*x;
dy = gradient(y);
dx = gradient(x);
dx_fun = @(z) spline(x,dx,z);
dy_fun = @(z) spline(x,dy,z);
for i=1:length(x)
yval(i,1)=integral(dy_fun,0,x(i),'RelTol',1e-10,'AbsTol',1e-12);
yval(i,1)=yval(i,1)/dx(i);
end
cumtrapz(dy)
The value of yval is [ 0
0.013638392857143
0.043333333333333
0.093415178571508
0.163392857142853
0.253400297619018
0.363392857142850
0.493415178572472
0.643333333334451
0.813638392858353
1.000000000000000]
and cumtrapz(dy) is [0 0.015000000000000 0.045000000000000 0.095000000000000 0.165000000000000 0.255000000000000 0.365000000000000 0.495000000000000 0.645000000000000 0.815000000000000 1.000000000000000]
The final value of integration matches but I have issues with intermediate values
integral() and cumtrapz() are not similar functions. cumtapz is the implementation of simple trapezoidal rule with fixed step-size, whereas integral() is a more advanced function that uses adaptive step-size. Therefore, the result can differ, and the value returned by integral will be more accurate.
Try decreasing fixed-step size for cumtrapz() function, and you will see that output is similar
x = 0:0.01:1;
Or even easier, trapz(x, dy_fn(x)).

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by