%% Moving Table Statistics
% Calculate moving statistics on the variables of a table.
%
% Load the outages.csv data set as a tall table. The data contains information about power outages.

T = tall(readtable('outages.csv'))

%
% Use matlab.tall.blockMovingWindow to apply a moving-window function to blocks of the tall table. Specify these options:
% blkstats as the block function to operate on complete blocks of data (included at the end of the example as a local function).
% A window size of 50 and a stride of 5.
% EndPoints as 'discard' to ignore incomplete windows of data. With this value, the windowfcn input can be specified as empty [] since only complete windows of data are operated on.
% The input table has six variables, but the two outputs are double-precision vectors. Specify scalar doubles as the value for OutputsLike so that the function permits this change in data type and size.

[A, B] = matlab.tall.blockMovingWindow([], @blkstats, 50, T, 'Stride', 5, ...
    'EndPoints', 'discard', 'OutputsLike', {1, 1});

%
% Preview a few rows in the results.

[A,B] = gather(head(A),head(B))

%
% The blkstats function calculates the moving median value of the Loss and Customers table variables in the first dimension using the specified window size. The function applies the Stride value to reduce the size of the output, and then it returns the results as two vectors.

function [out1, out2] = blkstats(info, t)
    a = movmedian([t.Loss t.Customers], info.Window, 1, 'omitnan', 'EndPoints', 'discard');
    a = a(1:info.Stride:end, :);
    out1 = a(:,1);
    out2 = a(:,2);
end

% Copyright 2018 The MathWorks, Inc.