Edit: I am redoing the solution because I found out that Matlab does not handle anonymous functions well. So I changed the call from an anonymous function to a normal function. Making this change:
Test 1
Comparison(40E3, 3E3)
Elapsed time is 21.731176 seconds.
Elapsed time is 251.327347 seconds.
|y2-y1| = 3.1519e-06
Test 2
Comparison(40E3, 1E3)
Elapsed time is 6.407259 seconds.
Elapsed time is 25.551116 seconds.
|y2-y1| = 2.8402e-07
Test 3
Comparison(20E3, 3E3)
Elapsed time is 10.484422 seconds.
Elapsed time is 125.033313 seconds.
|y2-y1| = 1.5462e-06
Test 4
Comparison(20E3, 1E3)
Elapsed time is 3.153404 seconds.
Elapsed time is 13.200649 seconds.
|y2-y1| = 1.5627e-07
The function is:
function Comparison(n, M)
u = rand(n, 1);
L = rand(M);
gamma = rand(M, 1);
tic
y1 = vectorized(u, L, gamma);
toc
tic
y2 = looped(u, L, gamma);
toc
disp(['|y2-y1| = ', num2str(norm(y2 - y1, 1))])
end
function y = vectorized(u, l, gamma)
global a Column
M = length(gamma);
Column = l' * gamma;
x = bsxfun(@plus, -(1:M)', (1:length(u)) + 1);
x(x < 1) = 1;
a = u(x);
a(1:M, 1:M) = a(1:M, 1:M) .* triu(ones(M));
a = a';
m = 1:size(a,1);
y = arrayfun(@VectorY , m)';
end
function yi = VectorY(j)
global a Column
yi = a(j,:) * Column;
end
function y = looped(U, l, gamma)
n = length(U);
M = length(gamma);
u = U';
L = l';
y = zeros(n, 1);
for i=1:n
y(i) = [u(i:-1:max(1,i-M+1)), zeros(1,(-i+M)*(i-M<0))] * L * gamma;
end
end