Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations waross on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

For Loop Vectorization

Status
Not open for further replies.

mstachowsky

Aerospace
Sep 30, 2006
4
0
0
GB
Hello there. I'm a beginner in matlab and have come up against a problem that, for the life of me, i can't vectorize or make run any more efficiently. the goal is this:

you have an 8 by 8 grid that is placed on top of a coordinate plane that goes from -100 to 100 in x and y. so each grid point is a 25x25 square.

You also have a two-D vector of x,y coordinates, and you want to search that vector and find out how many of its coordinates end up in each square. (this is the "coords" vector i'm pasting below). you then do a simple calculation for entropy, but that's part of the problem that i don't have much trouble with :)

so my question is: I'm using 2(!) nested for loops, and since your goal is to run this program for 1 million elements, it takes far too long to run. is there a way to vectorize (or at least make faster) this program without resorting to cutting out some of the times you run through the loops?

here's the code:

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

and of course we can assume that all variables that aren't already there have been declared and are full. coords is a 400x2 matrix.

Thanks,

Mike
 
Replies continue below

Recommended for you

Status
Not open for further replies.
Back
Top