[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

My vectorized code is slower than a loop

From: Dave Cottingham 2
Subject: My vectorized code is slower than a loop
Date: Mon, 17 Oct 2016 12:37:40 -0700 (PDT)

In the process of writing a routine to compute the Qn statistic of Croux and
Rousseeuw, I started from the Fortran code they published in their paper
(C&R, "Time-efficient algorithms for two highly robust estimators of scale")
and ran into unexpected trouble with one section. Here's a fairly literal
translation of the original, where x is an array of length n, and left and
right are also arrays of length n that contain integers:

w = zeros(1, n);
j = 1
for i = 1:n
  if(left(i) <= right(i))
    for jj = left(i):right(i)
      w(j) = x(i) - x(n+1-jj);
      j += 1;

Before we get to this section, left and right are such that at most n items
will get copied into w.

Not surprisingly, this code is pretty slow. I see no way to eliminate the
outside loop on i; but getting rid of the inside loop on jj is

w = zeros(1, n);
j = 1
for i = 1:n
  if(left(i) <= right(i))
    w(j:j+right(i)-left(i)) = x(i) - x(n+1-[left(i):right(i)]);
    j = j + right(i)-left(i)+1;

Problem is, the second, vectorized, code takes twice as long as the first,
non-vectorized, code.

Anybody have an idea why? I'm stumped.

I have attached a script that contains these two snippets, some setup, and
tics and tocs, for anyone who wants to play with it.

Dave Cottingham

looptest.m <>  

View this message in context:
Sent from the Octave - General mailing list archive at

reply via email to

[Prev in Thread] Current Thread [Next in Thread]