Hi
Here's how you can convert your code to use "fitcknn":
1. Train the KNN model using "fitcknn"
You only need to train the model once (outside the loop):
x = xlsread('DataTraining.xlsx');
training = x(:,1:4); % Features (assuming columns 1-4 are features)
group = x(:,5); % Labels (assuming column 5 is the class label)
% Train KNN model
Mdl = fitcknn(training, group);
2. Predict using the trained model
Use the "predict" function
for i = 1:20
y = xlsread('DataTesting.xlsx');
sample = y;
test = sample(:,1:4); % Features to test (columns 1-4)
% Predict using the trained model
result = predict(Mdl, test);
end
3. Save results
name = 'Result_KNN.xlsx';
result = [sample(:,1) sample(:,2) sample(:,3) sample(:,4) sample(:,5) result];
xlswrite(name, result);
Hope this helps!