I understand that you are trying to construct a prediction function based on a KNN Classifier and that you would like to loop over the examples and generate the predictions for them.
The following example will illustrate how to achieve the above :
function predictions = predictClass(mdlObj,testSamples, Y)
predictions = {};
for i = 1:length(testSamples)
ind = knnsearch(mdlObj, testSamples(i,:))
% using Y to get the class name name of the closest X data item
predictions(i) = Y(ind);
end
end
Please note that you will have to pass in “Y”(the labels for training set) as well because the “knnsearch” function outputs the index of the closest “X” (training set) data item. So, you will need the corresponding labels to get the class. You can refer to the following documentation for more information on the “knnsearch” function:
Alternatively, you can use the “fitcknn” function to train the model and the “predict” function to predict the classes of the test data, without the need to construct a separate prediction function. Please refer to the following documentation links for more information on the “fitcknn” and the “predict” functions: