Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I vectorize this for loop (matlab)

I appreciate advice on how I might vectorize the following for loop (matlab):

    summ=0;
    for i=1:lasti
         summ=summ+abs(newTS(m+i*k)-newTS(m+(i-1)*k));
    end

By vectorize I mean use matrix operations instead of the for loop. I have heard that vectorization is generally more efficient and quicker than for loops.

EDIT: Actually what I would really like to vectorize is below. I include it in case some brave soul wants to give it a shot...

   for j=1:length(kvec)
       k=kvec(j);
       for m=1:k
           lasti=floor((N-m)/k);
           Nfact=(N-1)/(lasti*k);
           summ=0;
           for i=1:lasti
                summ=summ+abs(newTS(m+i*k)-newTS(m+(i-1)*k));
           end
           L(m,j)=(summ*Nfact)/k;
           %Avg over m
           AvgL(j)=mean(L(:,j));
        end
    end
like image 348
ben Avatar asked Nov 23 '25 01:11

ben


1 Answers

Basically you want to sum all the distance between newTS(m+i*k) and newTS(m+(i-1)*k), so you can do something like this

summ = sum(abs(diff(newTS(m:k:m+lasti*k))))

I agree with you that in my experience with Matlab, matrix operation is usually MUCH faster than for loops. I try to avoid them as much as I can.

EDIT: I think replace the inner i loop should be good enough for you. Maybe you can replace the m loop by reshape newTS into a matrix, but since lasti is different for each m, it could be tricky in your case.

like image 50
LWZ Avatar answered Nov 24 '25 18:11

LWZ