function aligned_matrix = consensusMatrix(expBars, pA, pB, theoryBar,global_hca)
if nargin < 5
    global_hca =0;
end
    nExp = numel(expBars);
 if global_hca == 0
 
    % Find the global start and stop positions (in theoryBar space)
    min_start = inf;
    max_end = -inf;

    for i = 1:nExp
        len = numel(expBars{i});
        start_theory = pB{i} - pA{i} + 1;
        stop_theory = start_theory + len - 1;

        min_start = min(min_start, start_theory);
        max_end = max(max_end, stop_theory);
    end

    % Also include full theoryBar range
    min_start = min(min_start, 1);
    max_end = max(max_end, numel(theoryBar));

    total_length = max_end - min_start + 1;
    aligned_matrix = NaN(nExp + 1, total_length); % +1 for theoryBar

    % Align each expBar
    for i = 1:nExp
        exp = expBars{i};
        len = numel(exp);
        start_theory = pB{i} - pA{i} + 1;
        stop_theory = start_theory + len - 1;

        start_idx = start_theory - min_start + 1;
        stop_idx = start_idx + len - 1;

        aligned_matrix(i, start_idx:stop_idx) = exp;
    end

    % Place theoryBar in the last row
    theory_start = 1 - min_start + 1;
    theory_stop = theory_start + numel(theoryBar) - 1;
    aligned_matrix(end, theory_start:theory_stop) = theoryBar;
 else
    pos=pA;
    len=pB;

    % Create a placeholder matrix and place theory at the end
    aligned_matrix = NaN(nExp + 1, length(theoryBar));
    aligned_matrix(end,:)=theoryBar;

    % Fill in the whole matrix with each barcode
    for i = 1:nExp
       % until=find(~isnan(expBars{i}),1,'last');
        %aligned_matrix(i,pos{i}:pos{i}+length(expBars{i}(1:until))-1)=expBars{i}(1:until);
        aligned_matrix(i,pos{i}:pos{i}+length(expBars{i})-1)=expBars{i};
    end
 end


end
