How to convert knnclassify to fitcknn

1 vue (au cours des 30 derniers jours)
akbar muslim
akbar muslim le 17 Juil 2020
Réponse apportée : Sameer le 16 Mai 2025
i have script from youtube but still using knnclassify
please help me how to change it to fitcknn, because when directly change knnclassify to fitcknn it always error.

Réponses (1)

Sameer
Sameer le 16 Mai 2025
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!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by