Need help vectorizing for-loop

1. Oct 7, 2010

sjaakiejj

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 (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));
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.

2. Oct 11, 2010

Pythagorean

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