Path_Planning/homework_map.m

84 lines
3.1 KiB
Mathematica
Raw Normal View History

2025-05-27 21:44:25 +08:00
% AstarDijkstra
2025-05-13 17:54:52 +08:00
%
% 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0
map = [0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; % 1
0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0; % 2
0 0 0 1 1 1 1 0 0 1 0 0 0 0 0 1 1 0 0 0; % 3
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0; % 4
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0; % 5
1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 0 0 1 1; % 6
1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1; % 7
1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0; % 8
1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 0 0 0; % 9
1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0; %10
0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0; %11
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0; %12
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; %13
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; %14
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; %15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0; %16
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1; %17
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %18
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; %19
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0;]; %20
%
start = [2, 2];
goal = [19, 19];
% A*
2025-05-27 21:44:25 +08:00
path_Astar = Astar(map, start, goal);
% Dijkstra
path_Dijkstra = Dijkstras(map, start, goal);
2025-05-13 17:54:52 +08:00
2025-05-27 21:44:25 +08:00
visualize_path(map, start, goal, path_Astar, path_Dijkstra);
2025-05-13 17:54:52 +08:00
2025-05-27 21:44:25 +08:00
function visualize_path(map, start, goal, path_Astar, path_Dijkstra)
2025-05-13 17:54:52 +08:00
% 01
imagesc(map);
colormap(flipud(gray)); % 0 1
axis equal tight;
hold on;
%
plot(start(2), start(1), 'bo', 'MarkerSize', 10, 'LineWidth', 2);
%
plot(goal(2), goal(1), 'ro', 'MarkerSize', 10, 'LineWidth', 2);
2025-05-27 21:44:25 +08:00
if ~isempty(path_Astar)
2025-05-13 17:54:52 +08:00
%
2025-05-27 21:44:25 +08:00
if ~isequal(path_Astar(1,:), start)
path_Astar = [start; path_Astar];
2025-05-13 17:54:52 +08:00
end
%
2025-05-27 21:44:25 +08:00
if ~isequal(path_Astar(end,:), goal)
path_Astar = [path_Astar; goal];
2025-05-13 17:54:52 +08:00
end
% 线
2025-05-27 21:44:25 +08:00
plot(path_Astar(:,2), path_Astar(:,1), 'r-', 'LineWidth', 2); % 绿线
plot(path_Astar(:,2), path_Astar(:,1), 'ro', 'MarkerSize', 4, 'MarkerFaceColor', 'r'); %
plot(path_Dijkstra(:,2), path_Dijkstra(:,1), 'g-', 'LineWidth', 2); % 绿线
plot(path_Dijkstra(:,2), path_Dijkstra(:,1), 'go', 'MarkerSize', 4, 'MarkerFaceColor', 'g'); %
2025-05-13 17:54:52 +08:00
end
% 线
[rows, cols] = size(map);
for i = 1:rows+1
line([0.5, cols+0.5], [i-0.5, i-0.5], 'Color', 'k'); % 线
end
for j = 1:cols+1
line([j-0.5, j-0.5], [0.5, rows+0.5], 'Color', 'k'); % 线
end
set(gca, ...
'XTick', 1:cols, ...
'YTick', 1:rows, ...
'XTickLabel', 1:cols, ...
'YTickLabel', 1:rows, ...
'XAxisLocation', 'top', ... % x
'YDir', 'reverse'); % y
title('');
hold off;
end