Кто-нибудь может определить ошибки в коде гибридной GA PSO в Matlab? - PullRequest
0 голосов
/ 18 октября 2019

Индекс превышает размеры матрицы.

Ошибка в gapso_logic> update_lbest (строка 103) sm (1, 1) = cost_p (1, nPopSize);

Ошибка в gapso_logic (строка 46)local_best_position = update_lbest (current_fitness (i), local_best_position, nPopSize);

Ошибка в предложенном2 (строка 282) [best_position, best_fitness] = gapso_logic (6, x_corr, y_corr, energy)

function [best_position,best_fitness] = gapso_logic(CN,x,y,E)


    model=CreateModel(CN,x,y,E);
    disp('default Sensors parameters')
%     model
    CostFunction=@(tour) TourLength(tour,model);

    No_of_Sensors  = CN;   %input('Enter the number of Sensors :');
    nVars =No_of_Sensors;

        % parameters
    nPopSize = 100; %input('Enter the Value of Population Size (apprx 100):');
    nIters = 10; %input('Enter the number of Iterations (apprx 400):');

%% PSO Logic

CreatePopFcn = @CreatePop;
FitnessFcn = CostFunction;
UpdatePosition = @UpdatePop;

    % Set algorithm parameters

    constant = 0.95;
    c1 = 1.5;       %1.4944;  %2;
    c2 = 1.5;       %1.4944;    %2;
    w = 0.792 * constant;  

    % Allocate memory and initialize
    gBestScore = inf;
    fitness = inf * ones(nPopSize, nIters);

    current_position = CreatePopFcn(nPopSize, nIters);
    velocity = zeros(nPopSize, 1);
    local_best_position = current_position;        %local_best_position = x;


    % update lbest
    cost_p = inf * ones(1, nPopSize);  %feval(FUN, local_best_position');
    for i=1:nPopSize

        current_fitness(i) = FitnessFcn(current_position(i));
       % cost_p(i) = FitnessFcn(local_best_position(i, 1:nPlant));
    end
    lbest = update_lbest(current_fitness(i), local_best_position, nPopSize);

    for iter = 1 : nIters    
        if mod(iter,1000) == 0
            parents = randperm(nPopSize);
            for i = 1:nPopSize
                x(i,:) = (local_best_position(i,:) + local_best_position(parents(i),:))/2;
%                v(i,:) = local_best_position(parents(i),:) - x(i,:);
%                v(i,:) = (v(i,:) + v(parents(i),:))/2;
            end

        else
            % Update velocity
            v = w*v + c1*rand(nPopSize,nCity).*(local_best_position-x) + c2*rand(nPopSize,nCity).*(lbest-x);

            % Update position
            x = x + v;
            x = UpdatePosition(x);

        end

        % Update local_best_position
        cost_x = inf * ones(1, nPopSize);
        for i=1:nPopSize
            cost_x(i) = FitnessFcn(x(i, 1:nPlant));
        end

        s = cost_x<cost_p;
        cost_p = (1-s).*cost_p + s.*cost_x;
        s = repmat(s',1,nCity);
        local_best_position = (1-s).*local_best_position + s.*x;

        % update lbest
        lbest = update_lbest(cost_p, local_best_position, nPopSize);

        % update global best
        all_scores(:, iter) = cost_x;

        [cost,index] = min(cost_p);
        if (cost < gBestScore) 
            gbest = local_best_position(index, :);
            gBestScore = cost;
        end

        % draw current fitness
        figure(1);
        plot(iter,min(cost_x),'cp','MarkerEdgeColor','k','MarkerFaceColor','g','MarkerSize',8)
        hold on

        str=strcat('Best fitness: ', num2str(min(cost_x)));
        disp(str);

    end
end

% Function to update lbest
function lbest = update_lbest(cost_p, x, nPopSize)
    sm(1, 1)= cost_p(1, nPopSize);
    sm(1, 2:3)= cost_p(1, 1:2);
    [cost, index] = min(sm);
    if index==1
        lbest(1, :) = x(nPopSize, :);
    else
        lbest(1, :) = x(index-1, :);
    end

    for i = 2:nPopSize-1
        sm(1, 1:3)= cost_p(1, i-1:i+1);
        [cost, index] = min(sm);
        lbest(i, :) = x(i+index-2, :);
    end

    sm(1, 1:2)= cost_p(1, nPopSize-1:nPopSize);

    sm(1, 3)= cost_p(1, 1);
    [cost, index] = min(sm);
    if index==3
        lbest(nPopSize, :) = x(1, :);
    else
        lbest(nPopSize, :) = x(nPopSize-2+index, :);
    end    
end

1 Ответ

0 голосов
/ 18 октября 2019

Мне кажется, я нашел проблему:

  • Строка 46:
    lbest = update_lbest(current_fitness(i), local_best_position, nPopSize);
    Первый параметр: current_fitness(i).
    current_fitness(i) isскаляр (размер скаляра 1х1).

  • Строка 103:
    sm(1, 1)= cost_p(1, nPopSize);
    Когда nPopSize> 1 (предположим, nPopSize = 2), вы пытаетесь получить доступ к cost_p(1, 2), который превышает размеры матрицы, потому чтоcost_p это скаляр.

Скаляр в MATLAB считается матрицей размером 1x1.
По этой причине вы получаете «Индекс превышает размеры матрицы». ошибка.
Сообщение об ошибке сбивает с толку, потому что переменная скалярная, а не матрица.

Вы можете исправить строку 46 следующим образом:

lbest = update_lbest(current_fitness, local_best_position, nPopSize);

Я не уверен, является ли это правильным решением, потому что опубликованный вами код не является исполняемым как есть.
Я не знаюНе знаю, есть ли какие-либо другие проблемы в коде ...
Вы должны использовать отладчик , для отладки такого рода ошибок.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...