# Matlab syntax (1:end-1) - Explanation

Could someone explain me this code?

``````meas.jerk.time = (meas.acc.time(1:end-1) + meas.acc.time(2:end)) ./ 2;
``````

Assuming that meas.acc.data and meas.acc.time are vectors with the same number of elements, then diff on the data vector will return a numeric vector with one element fewer than the time vector, so meas.jerk.data and meas.jerk.time will likely have mismatching sizes.

But idk the syntax of this code. What does (1:end-1) mean or (2:end) ./2?

These are the indices of the arrays.

If you are using the `diff` function to approximate derivatives as finite differences, it is good to remember those formulas. An approximation for the first derivative, second order accurate, is The diff function returns differences between adjacent elements of the vector. So, the diff function is suitable to estimate derivatives on the midpoint between adjacent elements.

You did not provided enough information about your code/data, so I will try to illustrate it with a numerical example.

Given the polynomial

``````f = @(x) 0.2 + 25*x − 200*x.^2 + 675*x.^3 − 900*x.^4 + 400*x.^5;
``````

A series of equally spaced values of the independent and dependet variables is generated with:

``````x = 0:0.1:0.8;
y = f(x);
``````

The divided-differences approximations for the derivatives is merely the vector division of the y differences and the x differences:

``````dydx = diff(y)./diff(x)
``````

In order to develop a plot of the results, as the derivative is estimated in the midpoint of each interval, we must generate a vector for the x values for the midpoints:

``````n = length(x);
xm = (x(1:n−1)+x(2:n))./2;
``````

To compare with the analyical solution,

``````xa = 0:.01:.8;
ya = 25 − 400*xa + 3*675*xa.^2 − 4*900*xa.^3 + 5*400*xa.^4;
plot(xm,dydx,'o',xa,ya)
`````` This is what your code is doing. The jerk is the derivative of the acceleration, but it is estimated on the midpoint of each interval in the time vector. Your code is calculating these midpoints.

• Thank you very much! Oct 18 '19 at 8:51