Is there a priority queue in matlab? I am writing a Djikstra algorithm which is slower. Would like to use a queue to make the code run faster.
조회 수: 6 (최근 30일)
이전 댓글 표시
I am trying to write a Djikstra's algorithm. But it takes for ever to run for 1000x1000 matrix. I was wondering if there were any ways I could use a priority queue to sort my open list and make my code run faster.
function hMap = djikstra(B,R)
%B = Cost Map
%R = Initial Position of the Robot
fprintf('In Dijkstra');
hMap = Inf(length(B)); % Assigning infinity
hMap(R(1),R(2)) = 0 ; % source node
open = [];
open = [R(1),R(2),0];
closed = [];
closed = [closed; open(1,1:2)]; %Put current source node in closed
x = R(1);
y = R(2);
while(size(open) ~= 0)
if(x-1 ~=0)
if(sum(ismember(closed(:,1:2),[x-1,y],'rows'))== 0)
cost = hMap(x,y)+ B(x-1,y);
hMap(x-1,y) = min(cost,hMap(x-1,y));
open = [open;x-1,y,hMap(x-1,y)];
end
end
if(x+1 <= length(B))
if(sum(ismember(closed(:,1:2),[x+1,y],'rows'))== 0)
cost = hMap(x,y)+ B(x+1,y) ;
hMap(x+1,y) = min(cost,hMap(x+1,y));
open = [open;x+1,y,hMap(x+1,y)];
end
end
if(y-1 ~= 0)
if(sum(ismember(closed(:,1:2),[x,y-1],'rows'))== 0)
cost = hMap(x,y)+ B(x,y-1);
hMap(x,y-1) = min(cost, hMap(x,y-1));
open = [open;x,y-1,hMap(x,y-1)] ;
end
end
if(y+1 <= length(B))
if(sum(ismember(closed(:,1:2),[x,y+1],'rows'))== 0)
cost = hMap(x,y)+ B(x,y+1);
hMap(x,y+1) = min(cost,hMap(x,y+1));
open = [open;x,y+1,hMap(x,y+1)];
end
end
closed = [closed;x,y];
open = open(2:size(open,1),:); %Removing source element from the open list
open = unique(open,'rows');
open = sortrows(open,3); % Sorting w.r.t G Value
if(size(open) ~= 0)
x = open(1,1)
y = open(1,2)
end
end
end
댓글 수: 0
답변 (1개)
Image Analyst
2016년 10월 22일
It would be shorter if you used the built in shortestpath() function
path = shortestpath(G,s,t) computes the shortest path starting at source node s and ending at target node t. If the graph is weighted (that is, G.Edges contains a variable Weight), then those weights are used as the distances along the edges in the graph. Otherwise, all edge distances are taken to be 1.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Construction에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!