How Can I Vectorize Nested For-Loops in Matlab for Handwriting Recognition?

  • Thread starter Thread starter sjaakiejj
  • Start date Start date
AI Thread Summary
The discussion centers on the inefficiencies of using for-loops in Matlab for a handwriting recognition project, particularly when implementing the k-Nearest Neighbour (k-NN) classifier. The user has experience in Java and C++ but is struggling with Matlab's performance, especially with nested loops that lead to long processing times. They highlight that vectorizing even one of the loops could significantly reduce the number of iterations, thus improving efficiency. The dataset consists of images represented as vectors, and the user seeks advice on how to effectively vectorize the code to enhance performance. Suggestions are made regarding the potential for vectorization, especially concerning the handling of matrices in the k-NN function, indicating that the solution may depend on how the k-NN classifier processes the data.
sjaakiejj
Messages
1
Reaction score
0
Hi,

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:
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));
  end;
end;


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.
 
Physics news on Phys.org
Well, that depends on how knearest handles matrices:

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

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

Similar threads

Replies
2
Views
1K
Replies
2
Views
2K
Replies
1
Views
2K
Replies
4
Views
2K
Replies
8
Views
2K
Replies
2
Views
6K
Back
Top