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

  • Context: MATLAB 
  • Thread starter Thread starter sjaakiejj
  • Start date Start date
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.
 
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 4 ·
Replies
4
Views
4K
  • · Replies 4 ·
Replies
4
Views
11K
  • · Replies 5 ·
Replies
5
Views
4K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
5K
Replies
1
Views
4K
  • · Replies 7 ·
Replies
7
Views
4K
  • · Replies 3 ·
Replies
3
Views
2K