Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Need help vectorizing for-loop

  1. Oct 7, 2010 #1

    I've been a programmer in Java and C++ for about 4 years now, and recently started using Matlab for a small project for handwriting recognition.
    Matlab however is terribly inefficient when it comes to for-loops, making the code I currently use horribly slow, having to wait for minutes before the results come forward. I understand the basics of vectorization in code, using built-in commands such as sum and ./ .* and .^, however none of these seem to provide me with what I want.

    Note that vectorizing just one of the two for-loops would already make a huge difference, as it would mean it iterates 89700 times less.

    Data is a dataset of images represented as vectors (reshaped matrices with pixel information), and labels is what identifies these data samples to the digit they represent.

    Code (Text):

    wrong = zeros(300,1);
    numberOfSamples = 300;

    for k = 1:numberOfSamples
      for i = 1:numberOfSamples
          wrong(k) = wrong(k) + (knearest(k, data(i,:), data, labels) ~= labels(i,1));


    Knearest is the k-Nearest-Neighbour classifier, which classifies a datasample to a certain class. So my question here is, how do I vectorize this code, if it's possible at all? I'd imagine something's possible with k, where as i would become much harder.

    Thanks in advance.
  2. jcsd
  3. Oct 11, 2010 #2


    User Avatar
    Gold Member

    Well, that depends on how knearest handles matrices:

    Code (Text):

    N = 300;
    wrong = zeros(N,1);

    for k = 1:N
          wrong(k) = wrong(k) + (knearest(k, data, data, labels) ~= labels(i,1));
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook