If ts is the timeseries() variable then
extracts the data.
With your data being 20000 x 50 my guess is that you have 20000 measurements for each of 50 entities, rather than 50 measurements for each of 20000 entities. If I am correct, then you would want the y gradient:
[~, ygrad] = gradient(X, xstep, tstep);