Search code examples
matlabdata-processing

Function to lag table variables


Is a easy way to lag all of the variables in a table by a certain number of lags, replacing values with NaNs.

The table variable does not support the length function which causes matlab's built-in lagmatrix function to fail.

The environment is R2015a.

For a given array

a= magic(5);

a =

17    24     1     8    15
23     5     7    14    16
 4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

lagmatrix(a,3)
ans =
NaN   NaN   NaN   NaN   NaN
NaN   NaN   NaN   NaN   NaN
NaN   NaN   NaN   NaN   NaN
 17    24     1     8    15
 23     5     7    14    16

Attempting to run the same command on a table, yields the following error

a=array2table(magic(5))
a = 

Var1    Var2    Var3    Var4    Var5
____    ____    ____    ____    ____

17      24       1       8      15  
23       5       7      14      16  
 4       6      13      20      22  
10      12      19      21       3  
11      18      25       2       9  

lagmatrix(a,3)
Error using table/length (line 395)
Undefined function 'length' for input arguments of type 'table'.  Use the     HEIGHT,
WIDTH, or SIZE functions instead.

Error in lagmatrix (line 52)
if numel(Y) == length(Y)

Is there a simple command that will perform the above behaviour for a table variable in Matlab?


Solution

  • Why not just this?

    a = array2table(magic(5));     %// example table
    n = 3;                         %// lag
    a(n+1:end,:) = a(1:end-n,:);
    a{1:n,:} = NaN;