278 Accelerating MATLAB
®
Performance
for i = 1 : N
for j = 1 : T
Trials(i,j) = Trials(i,j) - mean2(Trials);
end
end
As user gevang explained,
856
by observing the pattern created by the recursive subtrac-
tion of the mean, we can infer the following recursive relationship:
m(k) = m(k-1) - m(k-1)/n % n=numel(Trials)=N*T
= m(k-1) * ((n-1)/n)
= m(1) * ((n-1)/n)^(k-1)
where m(1) is the average of the original matrix. The subtraction is applied iteratively, for
each element of the input matrix: the rst element subtracts m(1), the second subtracts m(2),
and so on. This leads to the following optimized (vectorized) form:
n = numel(Trials);
Trials = Trials - mean2(Trials)*reshape(((n-1)/n).^(0:n-1), T, N)';
5.7.12 Vectorizing Structure ...