Princeton Election Consortium

A first draft of electoral history. Since 2004

MATLAB code for unrolling a moving average

The following code takes a set of 3-day rolling-average data and extracts the set of 1-day data points with the least variance. Copyright 2008 Sam Wang.

%%%%%%%%%%%%%
%unroll.m
% Copyright 2008 by Sam Wang
clear
% Gallup sample data set
rollavg=[45 43 44 43 44 44 44 45 45 44 44 42 41 41 42 43 42 43 42 44 45 48 49 49 48 48 48 47 47 47 47 45 44 44 44 45 44 44 44 46 45 44 42 42 43 44 43 42 42 43];

days=length(rollavg);
stepsize=1;
work=[rollavg(1) rollavg(1) rollavg];
steps=[work(1)-15*stepsize:stepsize:work(1)+15];
numsteps=length(steps);
for i=1:numsteps
work(1)=steps(i);
work(2)=(3*rollavg(1)-work(1))/2;
work(3)=3*rollavg(1)-work(1)-work(2);
for j=1:days-1
work(j+3)=3*rollavg(j+1)-work(j+2)-work(j+1);
end
stdevs(i)=std(work);
end
[y,imin]=min(stdevs);
work(1)=steps(imin); % this value of first one-day poll minimizes the variance

for i=1:numsteps
work(2)=steps(i);
for j=1:days
work(j+2)=3*rollavg(j)-work(j+1)-work(j);
end
stdevs(i)=std(work);
end
[y,imin]=min(stdevs);
work(2)=steps(imin); % value of first one-day poll that minimizes variance

for j=1:days
work(j+2)=3*rollavg(j)-work(j+1)-work(j);
end

unrolled=work