From: "Mike Stachowsky" <mstachowsky@gmail.com>
Path: news.mathworks.com!newsfeed-00.mathworks.com!webcrossing
Newsgroups: comp.soft-sys.matlab
Subject: Vectorizing a nested for loop
Message-ID: <ef45c76.-1@webcrossing.raydaftYaTP>
Date: Sun, 12 Nov 2006 10:07:52 -0500
Lines: 38
NNTP-Posting-Host: 69.158.125.117
MIME-Version: 1.0
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
Xref: news.mathworks.com comp.soft-sys.matlab:378351



Hello all,

I'm a beginner to matlab and am looking at a code that runs for so
long it won't complete in a reasonable amount of time! Its a nested
for loop shown below:

      entropy = zeros(8,8);
            for k=1:8
            %now we figure out entropy
                 for h = 1:8
                     n=length(find(coords(:,1)<(-100 +(k*200/8)) &
coords(:,1)>(-100 + (k-1)*200/8) & coords(:,2) < (-100 +
(h*200/8)) & coords(:,2)>(-100 + (h-1)*200/8)));
                     if(n~=0)
                     entropy(k,h) = -(n/400)*(log(n/400));
                     else
                     entropy(k,h)=0;
                     end
                end
            end

now the problem is that i can't figure out how it can be vectorized.
here's what it does:

It searches an array of coordinates (x,y) of random dots spread about
the screen. it breaks up the entire plane into an 8x8 grid, and
finds how many of those dots are in each grid box.

The problem is that the dots are moved each time through, so in fact
this nested for loop is itself nested in another for loop that runs
one million times! clearly 8x8 a million times is unnacceptable for
runtime.

besides the trivial solution of running the 8x8 for loop once every
1000 times rather than each time through the loop, is there a way to
make this code run faster?

Mike