function overlap_heatmap(M)
% Calcola e visualizza l’overlap (%) dei neuroni attivi fra fattori di un ktensor.
%
% Regola: neuroni attivi = |zscore| > 2
%
% Input:
%   M : ktensor (output di gcp_opt)

    % Normalizza
    M = fixsigns(arrange(normalize(M,0)));
    U = M.U;
    R = size(U{1},2);

    % Trova neuroni attivi per ogni fattore
    activeSets = cell(R,1);
    for r = 1:R
        v = U{1}(:,r);
        z = (v - mean(v)) / std(v);
        activeSets{r} = find(abs(z) > 2);
    end

    % Calcola matrice overlap
    overlapMat = zeros(R,R);
    for i = 1:R
        Ai = activeSets{i};
        for j = 1:R
            Aj = activeSets{j};
            if isempty(Ai)
                overlapMat(i,j) = NaN;  % evita div/0
            else
                overlapMat(i,j) = 100 * numel(intersect(Ai,Aj)) / numel(Ai);
            end
        end
    end

    % Plot heatmap
    figure('Color','w','Name','Neuron overlap per factor');
    h = heatmap(overlapMat, 'Colormap', parula, 'ColorLimits',[0 100]);
    h.XLabel = 'Factor j';
    h.YLabel = 'Factor i';
    h.Title = 'Overlap of active neurons (%)';
end
