function ex9_2()
    % Pair-wise correlations of some curves (alignment score, ...)
    Initialize();
    X1 = getAllPatterns();
    X2 = removeOffset(X1);
    X3 = normalizeRows(X2);
    X4 = getCorrCoeff2D(X3);
    visualizeCorr(X1, X2, X3, X4);
    selfCorrelations = 1;
    DefineUIControl();

    
    function DefineUIControl()
    uicontrol(...
        'Style', 'pushbutton', ...
        'String', 'Toggle self-correlations', ...
        'Position', [300 20 150 20],...
        'Callback', @setSelfCorrelationsVisibility ...
        );        
    end

    function setSelfCorrelationsVisibility(source, callbackdata)
    selfCorrelations = 1 - selfCorrelations;
    X4_ = X4;
    if (selfCorrelations == 0)
       n1D = size(X4_,1);
       diagIndex = 1:n1D;
       diagIndex = (diagIndex - 1) * n1D + diagIndex;
       X4_(diagIndex) = 0;
    end
    subplot(2, 2, 4);
    imagesc(X4_);
    axis tight;
    %axis off;
    title('Pairwise-correlations');
    axis equal;
    colorbar;
    end
end
function [] = visualizeCorr(X1, X2, X3, X4)
    figure;

    subplot(2, 2, 1);
    imagesc(X1);
    axis tight;
    %axis off;
    title('Original');
    colorbar;
    
    subplot(2, 2, 2);
    imagesc(X2);
    axis tight;
    %axis off;
    title('Offset-removed');
    colorbar;

    subplot(2, 2, 3);
    imagesc(X3);
    axis tight;
    %axis off;
    title('Unity-norm');
    colorbar;

    subplot(2, 2, 4);
    imagesc(X4);
    axis tight;
    %axis off;
    title('Pairwise-correlations');
    axis equal;
    colorbar;
end
function X = getCorrCoeff2D(X)
    X = X * X';
end
function X = normalizeRows(X)
    [nPatterns, nPoints] = size(X);

    %Norms of different observation vectors (2D --> 1D)
    Norm_1D = sqrt(sum(X.^2, 2));

    %Repeating norms of different observation vectors (1D --> 2D)
    Norm_2D = repmat(Norm_1D, 1, nPoints);
    
    %Normalizing observation vectors
    X = X ./ Norm_2D;
end
function X = removeOffset(X)
    [nPatterns, nPoints] = size(X);

    %Averaging over all patterns (2D --> 1D)
    Xav_1D = mean(X, 1);

    %Repeating the 1D average (1D --> 2D)
    Xav_2D = repmat(Xav_1D, nPatterns, 1);
    
    %Removing the average
    X = X - Xav_2D;
end
function X = getAllPatterns()
    if (menu('Source of data', 'File', 'Simulation') == 1)
        filePath = uigetfile('*.*','Please select the data file');
        X = importdata(filePath);
        X = X.data;
    else
        nPatterns = 100;
        nPoints = 60;
        peakIndex = floor(nPoints * 0.40);
        peakHalfWidth = 3;
        allPeakIndices = peakIndex + (-peakHalfWidth:peakHalfWidth);
        nPeaks = 2 * peakHalfWidth + 1;
        noiseAmp = 0.5;
        X = randn(nPatterns, nPoints) + 1;
        for cntr = 1: nPatterns
            if (rand > 0.5)
                X(cntr,allPeakIndices) = noiseAmp * abs(randn(1, nPeaks));
            end
        end
    end
end
function Initialize()
    close all force;
    clear;
    clc;
end    
