% Reading |r_xy| off a scatter plot
% Textbook: Part I, "Uni-Variate Linear Least-Squares", ranking exercises on
% the correlation coefficient
%
% Two sets of four panels. Try to order each set by |r_xy| before looking at
% the printed values. Two cues decide: how straight the cloud is, and how
% tightly it hugs its trend. Panel (a) of set A is an exact quadratic
% relation with r_xy near zero. The noise differs from the textbook figure,
% so the printed values differ slightly from the ones quoted there.

clearvars; close all
rng(0)

N = 200;
x = linspace(-1, 1, N);
setA = {x, x.^2 + 0.1*randn(1, N); ...
        x, x + 0.1*randn(1, N); ...
        x, 0.5*x.^2 + x.^7 + 0.1*randn(1, N); ...
        x, x.^3 + 0.051*randn(1, N)};

wide = linspace(-2, 2, N);
setB = {wide, -wide + 0.175*randn(1, N); ...
        wide, wide + 0.1*randn(1, N); ...
        x, x + x.^2 + 0.25*randn(1, N); ...
        x, -x + 0.2*randn(1, N)};

sets = {setA, setB};
labels = 'abcd';
for s = 1:2
    figure
    tiledlayout(2, 2)
    fprintf('Set %c:\n', 'A' + s - 1)
    for i = 1:4
        [xi, yi] = sets{s}{i, :};
        c = corrcoef(xi, yi);
        fprintf('  (%c) r_xy = %+.4f\n', labels(i), c(1, 2))
        nexttile
        plot(xi, yi, '.')
        title(sprintf('(%c)', labels(i)))
        xlabel('X'); ylabel('Y')
        grid on
    end
end
