×
INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

For Loop Vectorization

For Loop Vectorization

For Loop Vectorization

(OP)
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

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Eng-Tips forums is a member-only feature.

Click Here to join Eng-Tips and talk with other members!


Resources