load fisheriris

%% Part 3 Categorical and numerical data

% The function myOwnGrp2idx is defined at the bottom.
% It generates a vector of integer labels from a vector of string labels

% compare myOwnGrp2idx with the equivalent built-in function grp2idx
assert(all(myOwnGrp2idx(species) == grp2idx(species)))

%% Part 4 Data visualization
X = meas;
y = grp2idx(species);

size(X) % the function returns the size of a matrix
size(y)

Xsetosa = X(species == "setosa", :);
Xversicolor = X(species == "versicolor", :);
Xvirginica = X(species == "virginica", :);

labels = {'sepal length','sepal width','petal length','petal width'};
pairs = combnk(1:4,2);

figure
plot2dsamples(Xsetosa, Xversicolor, Xvirginica, pairs, labels)
% One can infer e.g. the following rules from the plots.
% petal width < 0.75 => Setosa
% petal length < 2.5 => Setosa

pause(1)
figure
plothistogram(Xsetosa, Xversicolor, Xvirginica, labels)

pause(1)
figure
plotboxplots(X, species, labels)

%% Functions' definitions

function YNum = myOwnGrp2idx(Y)
    classes = unique(Y);
    YNum = zeros(length(Y), 1);
    for i = 1:length(classes)
        class = string(classes{i});
        YNum(class == Y) = i;
    end
end

function plot2dsamples(Xsetosa, Xversicolor, Xvirginica, pairs, labels)
    for k = 1:size(pairs, 1)
        jA = pairs(k, 1);
        jB = pairs(k, 2);
        subplot(2, 3, k)
        hold on
        plot(Xsetosa(:, jA), Xsetosa(:, jB), '.')
        plot(Xversicolor(:, jA), Xversicolor(:, jB), '.')
        plot(Xvirginica(:, jA), Xvirginica(:, jB), '.')
        xlabel(labels{jA})
        ylabel(labels{jB})
        if k == 1
            legend({"Setosa", "Versicolor", "Virginica"}, 'Location','northwest')
        end
    end
end

function plothistogram(Xsetosa, Xversicolor, Xvirginica, labels)
    for j = 1:length(labels)
        subplot(2,2,j)
        histogram(Xsetosa(:,j), 'FaceAlpha', .7, 'FaceColor', 'b');
        hold on
        histogram(Xversicolor(:,j), 'FaceAlpha', .7, 'FaceColor', 'g');
        hold on
        histogram(Xvirginica(:,j), 'FaceAlpha', .7, 'FaceColor', 'r');
        xlabel(labels{j})
        ylabel("count")
        if j == 4
            legend({"Setosa", "Versicolor", "Virginica"}, 'Location','northeast')
        end
    end
end

function plotboxplots(X, species, labels)
    for j = 1:length(labels)
        subplot(2,2,j)
        boxplot(X(:,j), species)
        xlabel("Species")
        ylabel(labels{j})
    end
end