I’m having a weird result with Matlab’s trapz function. I have two variables, zptest and omega, both of which are positive, 3000x2x1 arrays.
When I plot zptest vs omega (plot(zptest(:,1,1),omega(:,1,1)) the curve is clearly positive and should give a positive result when integrating. This is not the case, however, as shown below:
trapz(zptest(:,1,1),omega(:,1,1))
ans =
-0.049999940237341
just to prove that both omega and zptest are positive:
find(omega(:,1,1) < 0)
ans =
Empty matrix: 0-by-1
find(zptest(:,1,1) < 0)
ans =
Empty matrix: 0-by-1
I know I’m not giving any context to what I’m actually doing but this seems like a context independent problem. Does anyone have any idea what’s going on?
Try re-ordering x in ascending order (and y-values accordingly):
In
trapz(x,y)differentiation of x is applied through diff(x,1,1), i.e.[x(2:n,:) - x(1:n-1,:)].If your x is descending this will give negative dx. It doesn’t matter if it is positive or negative. However, inplotthe curve will appear positive-definite (you don’t actually see the order of points, just pairs from two vectors on a plane).Example (compare the following):