vectorization - Vectorize MATLAB for loop -


i have following lines of code

y = zeros(n, 1);  i=1:n      b = l * [u(i:-1:max(1,i-m+1));zeros((-i+m)*(i-m<0),1)];     y(i) = b' * gamma; end 

u nx1, gamma mx1 , l mxm

n takes large values, there ideas on how vectorize loop?

edit: redoing solution because found out matlab not handle anonymous functions well. changed call anonymous function normal function. making change:

test 1

comparison(40e3, 3e3) elapsed time 21.731176 seconds. elapsed time 251.327347 seconds. |y2-y1| = 3.1519e-06 

test 2

comparison(40e3, 1e3) elapsed time 6.407259 seconds. elapsed time 25.551116 seconds. |y2-y1| = 2.8402e-07 

test 3

comparison(20e3, 3e3) elapsed time 10.484422 seconds. elapsed time 125.033313 seconds. |y2-y1| = 1.5462e-06 

test 4

comparison(20e3, 1e3) elapsed time 3.153404 seconds. elapsed time 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 column     m = length(gamma);     column = l' * gamma;      x = bsxfun(@plus, -(1:m)', (1:length(u)) + 1);     x(x < 1) = 1;     = u(x);     a(1:m, 1:m) = a(1:m, 1:m) .* triu(ones(m));     = a';     m = 1:size(a,1);     y = arrayfun(@vectory , m)'; end  function yi = vectory(j) global 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);      i=1:n         y(i) = [u(i:-1:max(1,i-m+1)), zeros(1,(-i+m)*(i-m<0))] * l * gamma;     end end 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -