MATLAB: Trailing Sum Calculation using pre-defined kernel starting at incorrect cell

calculationfinancefinancialfor loopkernelloopsMATLAB and Simulink Student Suitesumtabletrailingsum

Table Z:
Goal: Calculating a 12-point trailing sum for any date point looking upward in the table, e.g. 20-May-2016 must display the sum of the shaded area (0.1768).
So far:
[rows, columns] = size(Z);
onesVector = ones(rows, 1);
kernel12t = [0;0;0;1;1;1;1;1;1;1;1;1;1;1;1]; % Kernel that computes
% the trailing 12 values
trailingSum12t = zeros(rows, columns);
for col = 4 : columns
thisColumn = Z{:, col}; % Extract all rows from this column.
cellSum12t = conv(onesVector, kernel12t, 'same');
valuesSum12t = conv(thisColumn, kernel12t, 'same');
trailingSum12t(:, col) = valuesSum12t;
end
The outcome of "trailingSum12t" is displayed below. However, the highlighted cell shouldn't be 0.1760 but 0.1768. Strangely I find the correct sum of the 12-point trailing kernel (0.1768) in a cell (row 8) where it shouldn't be.
Another issue is found in "cellSum12t" (see below): rows 551-554 should contain 12's!
The upper part of "cellSum12t" looks perfect though (see below):

Best Answer

I believe the key issue you are facing is the term: 'same'. When you pass this argument to "conv", it will make the output array the same size as the first input argument (in this case, rows-by-1), however it discards values on either end. In contrast, you will likely want to keep the first 'rows' elements of the output. For more information on convolution, there is a nice explanation on wikipedia .
For example, it seems to me that your "cellSum12t" should look like the output of the following code:
fakeData = ones(32,1);
kernel = ones(12,1);
output = conv(fakeData,kernel);
output = output(1:length(fakeData))
The second possible issue is the extra zeros in your kernel. They are not fundamentally wrong, but from your description of what you'd like to achieve, they do not seem needed. If you want to sum 12 values, including the current one, you can just use:
"kernel = ones(12,1)"
If you want to sum the 12 values above the current (for example), you could use
"kernel = [0; ones(12,1)]"
Related Question