knn code in matlab

Here is an example code to implement k-Nearest Neighbors (kNN) classification algorithm in MATLAB:

main.m
% Load sample data
load fisheriris

% Define number of neighbors
k = 5;

% Define the number of samples
N = size(meas, 1);

% Define the indices of train and test samples
trainIdx = 1:2:N;
testIdx = 2:2:N;

% Split the data into train and test sets
trainData = meas(trainIdx, :);
trainLabels = species(trainIdx);
testData = meas(testIdx, :);
testLabels = species(testIdx);

% Classify the test samples using kNN
predictedLabels = zeros(size(testLabels));
for i = 1:size(testData, 1)
    % Compute the distances between the test sample and all train samples
    distances = sum((trainData - testData(i, :)).^2, 2);

    % Sort the distances in ascending order
    [sortedDistances, sortedIdx] = sort(distances);

    % Take the k nearest neighbors
    kNearestLabels = trainLabels(sortedIdx(1:k));

    % Count the number of samples in each class
    counts = histc(kNearestLabels, unique(kNearestLabels));

    % Find the class with the maximum number of samples
    [~, maxIdx] = max(counts);

    % Assign the predicted label
    predictedLabels(i) = unique(kNearestLabels(maxIdx));
end

% Compute the accuracy of the classification
accuracy = sum(predictedLabels == testLabels) / numel(testLabels)
1201 chars
44 lines

In this example, we use the iris dataset to classify flowers based on their measurements using the kNN algorithm. We split the dataset into train and test sets, and then classify the test samples using the kNN algorithm. Finally, we compute the accuracy of the classification.

gistlibby LogSnag