索引的原因超出矩阵维度误差(matlab)?

时间:2017-10-16 22:54:48

标签: matlab optimization indexing dimensions

我正在使用启发式方法解决tsp优化问题,以下代码适用于所有euclidian tsplib实例排除 a280实例,它给出了“索引超出矩阵维度”错误,我可以'弄清楚为什么?

我发表了评论,因此希望代码很容易理解。错误发生在前一行代码i = mod(si(selected_edge)-1,n)+1;

n = size(a280,1); % n number of nodes

distances = dist(a280,a280');

savings = zeros(n);

lengths_obtained = [];

depot = 1 % depot is the central node

%% Test n number of solutions where each node is selected to be the depot
for depot = 1:n
    %% Compute the matrix of savings of each pair of nodes
    for i = 1:n    
        if i == depot
            continue;
        end
            savings(i,(i+1):n)=distances(i,depot)+distances(depot,(i+1):n)-distances(i,(i+1):n);
    end

    %% Initialisation steps
    minParent = 1:n;

    % Rank the savings s(i,j) and list them in descending order of
    % magnitude.
    [~,si] = sort(savings(:),'descend');
    si = si(1:fix(end/2));

    % Setting cache
    Nodes_depot = zeros(1,n); % binary vector, 1 if node i is disconnected from the depot, 0 otherwise
    Nodes_depot(depot) = 1;
    Nodes_depot_count = n-1;
    degrees = zeros(1,n); % number of edges linking a node

    selected_edge = 1;

    pairs_of_nodes = zeros(n,2); % listing the couples (i,j) of nodes linked together

    currentEdgeCount = 1;

    %% Pair nodes as long as more than 2 nodes are still connected to the depot 
    while Nodes_depot_count>2
        % Start with the edge (i,j) generating the topmost amount of
        % savings.
        i = mod(si(selected_edge)-1,n)+1;
        j = floor((si(selected_edge)-1)/n)+1;

        if Nodes_depot(i) == 0 && Nodes_depot(j)==0 &&    (minParent(i)~=minParent(j)) && i~=j && i~=depot && j~=depot
            degrees(i) = degrees(i)+1;
            degrees(j) = degrees(j)+1;
            pairs_of_nodes(currentEdgeCount,:) = [i,j];

            if minParent(i) < minParent(j)
                minParent(minParent == minParent(j)) = minParent(i);
            else
                minParent(minParent == minParent(i)) = minParent(j);            
            end

            currentEdgeCount = currentEdgeCount + 1;

            % Removing i and/or j if they now are paired with two other
            % nodes from partial tour.
            if degrees(i) == 2
                Nodes_depot(i) = 1;
                Nodes_depot_count = Nodes_depot_count - 1;
            end

            if degrees(j) == 2
                Nodes_depot(j) = 1;
                Nodes_depot_count = Nodes_depot_count - 1;
            end
        end
        selected_edge = selected_edge + 1;

    end

如果有人能把我推向正确的方向,我们将不胜感激。谢谢!

0 个答案:

没有答案