TimeSeriesLag { public static double[][] lag(double[] x, int maxLag) { if (maxLag < 1) { throw new IllegalArgumentException("maxLag should be greater than 0"); } if (x == null || maxLag > x.length) { throw new IllegalArgumentException("The length of array should be greater than maxLag"); } double[][] result = new double[maxLag][]; for (int lag = 1; lag <= maxLag; lag++) { double[] arr = new double[x.length - (maxLag - 1)]; for (int i = 0; i < x.length - (maxLag - 1); i++) { arr[i] = x[(maxLag - lag) + i]; } result[lag - 1] = arr; } return result; } private  TimeSeriesLag(); static double[][] lag(double[] x, int maxLag);  }
@Test public void testLag() throws Exception { double[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; double[][] lagged = TimeSeriesLag.lag(x, 1); Assert.assertTrue(lagged.length == 1); Assert.assertTrue(lagged[0].length == 10); Assert.assertArrayEquals(x, lagged[0], 0); lagged = TimeSeriesLag.lag(x, 2); Assert.assertTrue(lagged.length == 2); Assert.assertTrue(lagged[0].length == 9); Assert.assertTrue(lagged[1].length == 9); Assert.assertArrayEquals(new double[]{2, 3, 4, 5, 6, 7, 8, 9, 10}, lagged[0], 0); Assert.assertArrayEquals(new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9}, lagged[1], 0); x = new double[] { 1, 2, 3 }; lagged = TimeSeriesLag.lag(x, 3); Assert.assertTrue(lagged.length == 3); Assert.assertTrue(lagged[0].length == 1); Assert.assertTrue(lagged[1].length == 1); Assert.assertTrue(lagged[2].length == 1); Assert.assertArrayEquals(new double[]{3}, lagged[0], 0); Assert.assertArrayEquals(new double[]{2}, lagged[1], 0); Assert.assertArrayEquals(new double[]{1}, lagged[2], 0); }
@Test public void testErrorStates() { try { TimeSeriesLag.lag(new double[]{1,2}, 3); Assert.fail(); } catch (IllegalArgumentException ex) { } try { TimeSeriesLag.lag(null, -6); Assert.fail(); } catch (IllegalArgumentException ex) { } }