% Prompt the user for the type of opinion (H or I)
opinionType = input('Enter the opinion type (H or I): ', 's');

% Load the Excel file
excelFileName = 'criteriaexperts.xlsx'; % Replace with your actual filename
sheetNames = sheetnames(excelFileName);

% Prompt the user for maximum and minimum ranking scale values
maxScaleValue = input('Enter the maximum ranking scale value: ');
minScaleValue = input('Enter the minimum ranking scale value: ');

% Create a new Excel file for weights and consistency information
resultFileName = 'weights_and_consistency.xlsx';


% Loop through each sheet in the Excel file
for sheetIndex = 1:length(sheetNames)
    sheetName = sheetNames{sheetIndex};
    
    % Read the data from the specified columns (H or I)
    if strcmpi(opinionType, 'H')
        expertOpinion = xlsread(excelFileName, sheetName, 'H:H');
    elseif strcmpi(opinionType, 'I')
        expertOpinion = xlsread(excelFileName, sheetName, 'I:I');
    else
        error('Invalid opinion type. Use either ''H'' or ''I''.');
    end

    % Rank the criteria based on expert opinion
    [~, rankedIndices] = sort(expertOpinion, 'descend');
    numCriteria = length(rankedIndices);

    % Automatically assign scale values based on rank and user input
    pairwiseMatrix = zeros(numCriteria);

    for i = 1:numCriteria
        for j = i:numCriteria
            if i == j
                pairwiseMatrix(i, j) = 1; % Diagonal elements set to 1
            else
                % Scale the values based on the rank and user input
                scaleValue = round(minScaleValue + (numCriteria - abs(rankedIndices(i) - rankedIndices(j))) / numCriteria * (maxScaleValue - minScaleValue));

                pairwiseMatrix(rankedIndices(i), rankedIndices(j)) = scaleValue;
                pairwiseMatrix(rankedIndices(j), rankedIndices(i)) = 1 / scaleValue;
            end
        end
    end

    % Normalize the matrix
    normalizedMatrix = bsxfun(@rdivide, pairwiseMatrix, sum(pairwiseMatrix));

    % Calculate weights by summing the normalized matrix row-wise
    weights = sum(normalizedMatrix, 2) / numCriteria;

    % Display weights
    disp(['Weights for ' sheetName ':']);
    disp(weights);

    % Write the title to J1 and weights to J2 onwards
    writematrix(["AHP Weight"; weights], resultFileName, 'Sheet', sheetName, 'Range', 'J1');

end
