% S = lagdist(X,T[,d]) Lagged distances of a vector time series
%
% X(t,:) is a D-dim vector at time t, for t=1,2...N tdist computes the lagged
% squared Euclidean distances |X(t+T,:) - X(t,:)|² for t=1,2...N-T, where T is
% a nonnegative integer (the lag). Other distances are possible, eg the L1:
% |X(t+T,:) - X(t,:)|.
%
% This is equal to the Tth diagonal of sqdist(T).
%
% In:
%   X: NxD matrix of N row D-dim vectors.
%   T: list of nonnegative integers, the lag values.
%   d: the type of distance (2: squared Euclidean, 1: L1 norm or Hamming).
%      Default: 2.
% Out:
%   S: Nx? array of lagged distances, where ? is the length of T, padded with
%      NaNs. That is, the lagged distances for T(i) are in S(1:N-T(i),i), and
%      S(N-T(i)+1:N,i) are NaNs.
%
% Any non-mandatory argument can be given the value [] to force it to take
% its default value.

% Copyright (c) 2016 by Miguel A. Carreira-Perpinan

function S = lagdist(X,T,d)

% ---------- Argument defaults ----------
if ~exist('d','var') || isempty(d) d = 2; end;
% ---------- End of "argument defaults" ----------

lT = length(T); S = NaN(size(X,1),lT);

switch d
 case 2
  for i=1:lT
    S(1:end-T(i),i) = sum((X(T(i)+1:end,:) - X(1:end-T(i),:)).^2,2);
  end
 case 1
  for i=1:lT
    S(1:end-T(i),i) = sum(abs(X(T(i)+1:end,:) - X(1:end-T(i),:)),2);
  end
end

