error :
Too many output arguments.

Error in nsga2_300 (line 44)
        SP_values(run), DU_values(run)] = calculate_metrics(paretoFront, true_pareto);


my code:
clc;
clear;
close all;

% Set problem parameters
NPop = 100;  % Population size
T = 100;     % Number of iterations
dim = 30;    % Number of decision variables
lb = zeros(1, dim);  % Lower bound
ub = ones(1, dim);   % Upper bound
num_runs = 2;  % Number of runs for statistical evaluation
max_archive = 100;  % Maximum archive size

% Storage for metrics
GD_values = zeros(num_runs, 1);
IGD_values = zeros(num_runs, 1);
Spacing_values = zeros(num_runs, 1);
Spread_values = zeros(num_runs, 1);
SP_values = zeros(num_runs, 1);
DU_values = zeros(num_runs, 1);

% store best pareto
paretoFronts = cell(num_runs, 1);
paretoSets = cell(num_runs, 1);


%% Run NSGA-II Multiple Times
for run = 1:num_runs
    fprintf('Run #%d/%d\n', run, num_runs);
    
   % Run NSGA-II
   [paretoFront, paretoSet] = NSGA2(NPop, T, lb, ub, dim, max_archive);
    
     % Store Pareto front and set
    paretoFronts{run} = paretoFront;
    paretoSets{run} = paretoSet;
    
    
    % Get True Pareto Front
    true_pareto = get_true_pareto();
    
    % Update metrics calculation
    [GD_values(run), IGD_values(run), Spacing_values(run), Spread_values(run), ...
        SP_values(run), DU_values(run)] = calculate_metrics(paretoFront, true_pareto);
end

% Update the metrics array when displaying statistics
metrics = {GD_values, IGD_values, Spacing_values, Spread_values, SP_values, DU_values};
metric_names = {'GD', 'IGD', 'Spacing', 'Spread', 'SP', 'DU'};

% Find the best run based on the chosen metric (e.g., IGD)
[~, best_run_idx] = min(IGD_values);
best_paretoFront = paretoFronts{best_run_idx};
best_paretoSet = paretoSets{best_run_idx};

% Print results
fprintf('\nPerformance Metrics over %d runs:\n', num_runs);
for i = 1:length(metrics)
    fprintf('\n%s Statistics:\n', metric_names{i});
    fprintf('  Best    = %.4f\n', min(metrics{i}));
    fprintf('  Average = %.4f\n', mean(metrics{i}));
    fprintf('  Median  = %.4f\n', median(metrics{i}));
    fprintf('  Worst   = %.4f\n', max(metrics{i}));
    fprintf('  Std Dev = %.4f\n', std(metrics{i}));
end

%% Plot Results

% Plot the best Pareto Front
figure;
plot(best_paretoFront(:,1), best_paretoFront(:,2), 'ro', 'MarkerSize', 6, 'MarkerFaceColor', 'r');
hold on;
plot(true_pareto(:,1), true_pareto(:,2), 'b--', 'LineWidth', 1.5);
xlabel('f1');
ylabel('f2');
title(sprintf('Best Pareto Front (Run #%d) for ZDT2 using NSGA-II', best_run_idx));
legend('Obtained Pareto Front', 'True Pareto Front');
grid on;
hold off;

% Display metrics for the best run
fprintf('\nBest Run #%d Metrics:\n', best_run_idx);
fprintf('GD    = %.4f\n', GD_values(best_run_idx));
fprintf('IGD   = %.4f\n', IGD_values(best_run_idx));


% Plot Pareto Front
figure;
plot(paretoFront(:,1), paretoFront(:,2), 'ro', 'MarkerSize', 6, 'MarkerFaceColor', 'r');
hold on;
plot(true_pareto(:,1), true_pareto(:,2), 'b--', 'LineWidth', 1.5);
xlabel('f1');
ylabel('f2');
title('Pareto Front for zdt2 using NSGA-II');
legend('Obtained Pareto Front', 'True Pareto Front');
grid on;
hold off;

% Plot the results
figure;
plot(paretoFront(:,1), paretoFront(:,2), 'ro', 'DisplayName', 'NSGA-II');
xlabel('f1');
ylabel('f2');
title('NSGA-II Pareto Front for zdt2');
legend('show');
grid on;

function [paretoFront, paretoSet] = NSGA2(NPop, T, lb, ub, dim, max_archive)
    % Initialize population
    pop = initialization(NPop, dim, ub, lb);
    fitness = evaluate_population(pop, @zdt2);

    for gen = 1:T
        % Non-dominated sorting
        [fronts, ranks] = non_dominated_sort(fitness);
        
        % Create mating pool using binary tournament selection
        mating_pool = tournament_selection(pop, ranks, NPop);
        
        % Generate offspring using SBX crossover and polynomial mutation
        offspring = simulated_binary_crossover(mating_pool, dim, 20, 0.9);
        offspring = polynomial_mutation(offspring, 1/dim, 20);
        
        % Evaluate offspring
        offspring_fitness = evaluate_population(offspring, @zdt2);
        
        % Combine population and offspring
        comb_pop = [pop; offspring];
        comb_fitness = [fitness; offspring_fitness];
        
        % Non-dominated sorting on combined population
        [fronts, ~] = non_dominated_sort(comb_fitness);
        
        % Create new population with archive size limit
        [pop, fitness] = select_new_population(comb_pop, comb_fitness, fronts, max_archive);
        
        % Display generation progress
        disp(['Generation #', num2str(gen), ' completed.']);
    end

    % Return last population as Pareto front
    paretoFront = fitness;
    paretoSet = pop;
end

% ... [Rest of the functions remain the same as in your original code]
% ... [Rest of the functions remain the same as in your original code]

function pop = initialization(NPop, dim, ub, lb)
    pop = rand(NPop, dim) .* (ub - lb) + lb;
end

function fitness = evaluate_population(pop, FITNESSFCN)
    fitness = zeros(size(pop, 1), 2);  % Assuming 2 objectives
    for i = 1:size(pop, 1)
        fitness(i, :) = FITNESSFCN(pop(i, :));
    end
end

function [fronts, rank] = non_dominated_sort(fitness)
    num_individuals = size(fitness, 1);
    domination_count = zeros(num_individuals, 1);
    dominated_set = cell(num_individuals, 1);
    rank = zeros(num_individuals, 1);

    fronts = cell(1);
    for i = 1:num_individuals
        for j = 1:num_individuals
            if i ~= j
                if dominates(fitness(i, :), fitness(j, :))
                    dominated_set{i} = [dominated_set{i}, j];
                elseif dominates(fitness(j, :), fitness(i, :))
                    domination_count(i) = domination_count(i) + 1;
                end
            end
        end
        
        if domination_count(i) == 0
            rank(i) = 1;
            fronts{1} = [fronts{1}, i];
        end
    end
    
    current_front = 1;
    while ~isempty(fronts{current_front})
        next_front = [];
        for i = fronts{current_front}
            for j = dominated_set{i}
                domination_count(j) = domination_count(j) - 1;
                if domination_count(j) == 0
                    rank(j) = current_front + 1;
                    next_front = [next_front, j];
                end
            end
        end
        current_front = current_front + 1;
        fronts{current_front} = next_front;
    end
    fronts = fronts(1:current_front-1);
end

function is_dominated = dominates(x, y)
    is_dominated = all(x <= y) && any(x < y);
end

function selected_pop = tournament_selection(pop, ranks, num_selected)
    selected_pop = zeros(num_selected, size(pop, 2));
    for i = 1:num_selected
        candidates = randperm(size(pop, 1), 2);
        if ranks(candidates(1)) < ranks(candidates(2))
            selected_pop(i, :) = pop(candidates(1), :);
        else
            selected_pop(i, :) = pop(candidates(2), :);
        end
    end
end

function offspring = simulated_binary_crossover(pop, num_vars, eta_c, crossover_prob)
    offspring = zeros(size(pop));
    for i = 1:2:size(pop, 1)
        parent1 = pop(i, :);
        parent2 = pop(i+1, :);
        child1 = parent1;
        child2 = parent2;
        if rand < crossover_prob
            for j = 1:num_vars
                if rand <= 0.5
                    if abs(parent1(j) - parent2(j)) > 1e-14 % Avoid division by nearly zero
                        beta = 1.0 + (2*min(parent1(j), parent2(j)) / abs(parent1(j) - parent2(j)));
                        alpha = 2.0 - beta^(-(eta_c+1));
                        rand_num = rand;
                        if rand_num <= 1.0/alpha
                            beta_q = (rand_num*alpha)^(1.0/(eta_c+1));
                        else
                            beta_q = (1.0/(2.0 - rand_num*alpha))^(1.0/(eta_c+1));
                        end
                        child1(j) = 0.5*((1 + beta_q)*parent1(j) + (1 - beta_q)*parent2(j));
                        child2(j) = 0.5*((1 - beta_q)*parent1(j) + (1 + beta_q)*parent2(j));
                    else
                        child1(j) = parent1(j);
                        child2(j) = parent2(j);
                    end
                else
                    child1(j) = parent1(j);
                    child2(j) = parent2(j);
                end
            end
        end
        offspring(i, :) = child1;
        offspring(i+1, :) = child2;
    end
end

function mutated_pop = polynomial_mutation(pop, mutation_prob, eta_m)
    num_vars = size(pop, 2);
    mutated_pop = pop;
    for i = 1:size(pop, 1)
        for j = 1:num_vars
            if rand < mutation_prob
                r = rand;
                if r < 0.5
                    delta = (2 * r)^(1/(eta_m + 1)) - 1;
                else
                    delta = 1 - (2 * (1 - r))^(1/(eta_m + 1));
                end
                mutated_pop(i, j) = pop(i, j) + delta;
                mutated_pop(i, j) = min(max(mutated_pop(i, j), 0), 1);
            end
        end
    end
end

function [pop, fitness] = select_new_population(comb_pop, comb_fitness, fronts, NPop)
    pop = [];
    fitness = [];
    for i = 1:length(fronts)
        if size(pop, 1) + length(fronts{i}) > NPop
            break;
        end
        pop = [pop; comb_pop(fronts{i}, :)];
        fitness = [fitness; comb_fitness(fronts{i}, :)];
    end
    
    remaining = NPop - size(pop, 1);
    if remaining > 0
        selected_front = fronts{i};
        distances = crowding_distance(comb_fitness(selected_front, :));
        [~, sorted_indices] = sort(distances, 'descend');
        selected = selected_front(sorted_indices(1:remaining));
        pop = [pop; comb_pop(selected, :)];
        fitness = [fitness; comb_fitness(selected, :)];
    end
end

function distances = crowding_distance(fitness)
    num_individuals = size(fitness, 1);
    num_objectives = size(fitness, 2);
    distances = zeros(num_individuals, 1);
    for m = 1:num_objectives
        [sorted_values, sorted_idx] = sort(fitness(:, m));
        distances(sorted_idx(1)) = inf;
        distances(sorted_idx(end)) = inf;
        for i = 2:num_individuals-1
            range = sorted_values(end) - sorted_values(1);
            if range > 0
                distances(sorted_idx(i)) = distances(sorted_idx(i)) + ...
                (sorted_values(i+1) - sorted_values(i-1)) / range;
            end
        end
    end
end
function f = zdt2(x)
    f1 = x(1);
    g = 1 + 9 * sum(x(2:end)) / (length(x) - 1);
    h = 1 - (f1 / g)^2;
    f2 = g * h;
    f = [f1, f2];
end

% ------------------- True Pareto Front Function -------------------
function true_pareto = get_true_pareto()
    % Generate the true Pareto front for ZDT2
    num_points = 1000;
    f1 = linspace(0, 1, num_points)';
    f2 = 1 - (f1).^2;
    true_pareto = [f1, f2];
end

%% Performance Metrics Functions

%% Performance Metrics Functions

function [GD, IGD, Spacing, Spread, DU] = calculate_metrics(obtained_pf, true_pf)
    GD = generational_distance(obtained_pf, true_pf);
    IGD = inverted_generational_distance(obtained_pf, true_pf);
    Spacing = spacing_metric(obtained_pf);
    Spread = spread_metric(obtained_pf, true_pf);
    DU = distribution_uniformity(obtained_pf);
end

function gd = generational_distance(obtained_pf, true_pf)
    if isempty(obtained_pf)
        gd = Inf;
        return;
    end
    distances = zeros(size(obtained_pf, 1), 1);
    for i = 1:size(obtained_pf, 1)
        dist_to_true = sqrt(sum((true_pf - obtained_pf(i,:)).^2, 2));
        distances(i) = min(dist_to_true);
    end
    p = 2;
    gd = (sum(distances.^p) / size(obtained_pf, 1))^(1/p);
end

function igd = inverted_generational_distance(obtained_pf, true_pf)
    if isempty(obtained_pf)
        igd = Inf;
        return;
    end
    distances = zeros(size(true_pf, 1), 1);
    for i = 1:size(true_pf, 1)
        dist_to_obtained = sqrt(sum((obtained_pf - true_pf(i,:)).^2, 2));
        distances(i) = min(dist_to_obtained);
    end
    p = 2;
    igd = (sum(distances.^p) / size(true_pf, 1))^(1/p);
end

function spacing = spacing_metric(obtained_pf)
    if size(obtained_pf, 1) < 2
        spacing = Inf;
        return;
    end
    % Sort solutions
    sorted_pf = sortrows(obtained_pf);
    n = size(sorted_pf, 1);
    
    % Calculate distances between consecutive points
    distances = sum(abs(diff(sorted_pf)), 2);  % Manhattan distance
    d_bar = mean(distances);
    
    spacing = sqrt(sum((distances - d_bar).^2) / (n - 1));
end

function spread = spread_metric(obtained_pf, true_pf)
    if size(obtained_pf, 1) < 2
        spread = Inf;
        return;
    end
    
    % Identify extreme points in the true Pareto front
    f1_min = min(true_pf(:,1));
    f2_min = min(true_pf(:,2));
    extreme_points = [f1_min, max(true_pf(:,2)); max(true_pf(:,1)), f2_min];
    
    % Calculate distances to the extreme points
    df = zeros(1, 2);
    for i = 1:2
        dist_to_obtained = sqrt(sum((obtained_pf - extreme_points(i,:)).^2, 2));
        df(i) = min(dist_to_obtained);
    end
    
    % Calculate distances between consecutive points in the obtained Pareto front
    sorted_pf = sortrows(obtained_pf);
    distances = sqrt(sum(diff(sorted_pf).^2, 2));
    d_bar = mean(distances);
    
    spread = (sum(df) + sum(abs(distances - d_bar))) / (sum(df) + length(distances) * d_bar);
end

function du = distribution_uniformity(obtained_pf)
    if size(obtained_pf, 1) < 3
        du = 0;
        return;
    end
    
    % Sort based on the first objective for sequential distance calculation
    sorted_pf = sortrows(obtained_pf);
    n = size(sorted_pf, 1);
    
    % Calculate pairwise distances between consecutive solutions
    distances = sqrt(sum(diff(sorted_pf).^2, 2));
    mean_dist = mean(distances);
    
    % Coefficient of Variation (CV)
    std_dist = std(distances);
    cv = std_dist / mean_dist;
    
    % Distribution Uniformity metric
    du = 1 / (1 + cv);
end