% Load the Iris dataset
load fisheriris;
true_labels = grp2idx(species); % Convert species names to numeric labels

% Perform hierarchical clustering (or k-means clustering if already done)
Y = pdist(meas);                % Pairwise distances
Z = linkage(Y, 'average');       % Create linkage
cluster_labels = cluster(Z, 'maxclust', 3); % Create 3 clusters

% Calculate purity
unique_clusters = unique(cluster_labels);
purity = 0;

for i = 1:length(unique_clusters)
    % Find points in the current cluster
    cluster_points = true_labels(cluster_labels == unique_clusters(i));
    
    % Find the most common true label in the cluster
    mode_label = mode(cluster_points);
    
    % Count how many points have the most common label
    num_correct = sum(cluster_points == mode_label);
    
    % Add to purity score
    purity = purity + num_correct;
end

% Calculate overall purity by dividing by the total number of points
purity = purity / length(true_labels);
disp(['Purity of clusters: ' num2str(purity)]);