Function "diff" and the loss of an element in the array
69 views (last 30 days)
I have an issue with MATLAB, specifically related to a "diff" operation that is causing the loss of an element. The "diff" function in MATLAB is used to calculate the differences between consecutive elements in an array or matrix. I am using this function to calculate the derivate of an array.
It is clear to me that the resulting vector must have one less element. However, I need to perform the "diff" operation twice on the same array (resulting in an array with two less elements), and the issue I'm facing is that I don't know whether the vector is losing an element at the beginning or at the end. Initially, I thought it might be at the beginning. But when I compare the result of this operation with a reference value, it seems to be shifted on the axis. How can I be sure of this?
PS: It really makes a difference in my implementation.
More Answers (2)
dpb on 13 Sep 2023
diff is defined as x(i+1)-x(i) for i=2:numel(x). But, MATLAB arrays are always 1-based so the result of x(2)-x(1) is in the first location of the result vector. You don't really "lose" anything, but the location of the nth position corresponding to the initial vector does move down each successive operation...
Easy enough to illustrate numerically...
7 6 13 9 10 10 19 2 6 9
-1 7 -4 1 0 9 -17 4 3
8 -11 5 -1 9 -26 21 -1
Oftentimes it is convenient for coding purposes to prepend to the result to maintain the same length;
William Rose on 13 Sep 2023
Edited: William Rose on 13 Sep 2023
[edit: changed the code for plotting d2xdt2. The plotted result is unchanged, but the new verison of the code is more robust, because it will put d2xdt2 at the correct horizontal location, even if delta T is not unity.]
You can answer your own question by experiment.
disp(x); disp(dxdt); disp(d2xdt2)
You can see that the times associated with the second derivative are offset by 1 sample at the beginning and by 1 at the end. Plot the results as shown:
subplot(311); plot(t,x,'-r.'); ylabel('X'); grid on
subplot(312); plot(t(1:end-1)+.5,dxdt,'-g.'); ylabel('dX/dt'); grid on
ylabel('d^2X/dt^2'); xlabel('Time'); xlim([0 7]); grid on
The plots agree with the analytical solution for the first and second derivatives of x=t^3.