
% Time Series Disaggregation (TSD)

% n=number of HF data
% m=number LF data
% r=number of independant variables
% k=number of HF data between two consequent LF data
% beta[r*1]=parameters of regression
% Y[m*1]=LF dependant data
% X[n*1]=HF dependant data
% Z[n*r]=HF independant data

clear all
clc
load EX1

m=length(Y(:,1));
c=length(Y(1,:));
n=length(Z(:,1));
r=length(Z(1,:));
k=n/m;

% Constructing difference matrix D[n*n]

D=zeros(n,n);
D(1,1)=1;
for i=2:n
    for j=2:n
        if i==j
            D(i,j-1)=-1;
            D(i,j)=1;
        else
        end
    end
end

% Calculating A[n*n]

A=D'*D;

% Constructing aggregation matrix B[n*m]

B=zeros(n,m);
c0=0;
for j=1:m
    c0=c0+1;
    for i0=(c0-1)*k+1:c0*k
        B(i0,j)=1;
    end
end

% Calculating beta and X

for q=1:c
    beta(:,q)=inv(Z'*B*inv(B'*inv(A)*B)*B'*Z)*Z'*B*inv(B'*inv(A)*B)*Y(:,q);
    X(:,q)=Z*beta(:,q)+inv(A)*B*inv(B'*inv(A)*B)*(Y(:,q)-B'*Z*beta(:,q));
    q
end
