rrt*算法matlab代码
时间: 2023-09-06 13:10:18 浏览: 228
以下是一个简单的MATLAB实现RRT*算法的代码:
```matlab
clc; clear all; close all;
start_point = [0, 0];
goal_point = [8, 8];
max_iter = 5000;
delta_q = 0.5;
goal_radius = 0.5;
obstacle_radius = 1;
q_start.cost = 0;
q_start.parent = 0;
q_start.pos = start_point;
nodes(1) = q_start;
figure(1)
hold on
plot(start_point(1), start_point(2), 'ro', 'MarkerSize',10,'MarkerFaceColor','r')
plot(goal_point(1), goal_point(2), 'go', 'MarkerSize',10,'MarkerFaceColor','g')
rectangle('Position',[2,2,2,2],'FaceColor',[0 .5 .5])
rectangle('Position',[5,5,2,2],'FaceColor',[0 .5 .5])
axis([-1 10 -1 10])
axis square
grid on
for i = 2:max_iter
q_rand = [rand(1)*10, rand(1)*10];
% Find nearest node
[q_near, q_near_ind] = find_nearest(q_rand, nodes);
q_new = steer(q_near, q_rand, delta_q);
if obstacle_free(q_near, q_new, obstacle_radius)
% Find nearby nodes
near_inds = find_near(q_new, nodes, delta_q * 3);
% Choose parent
q_min = q_near;
C_min = q_new.cost + cost(q_near, q_new);
for j = 1:length(near_inds)
q_near_n = nodes(near_inds(j));
if obstacle_free(q_near_n, q_new, obstacle_radius) && q_near_n.cost + cost(q_near_n, q_new) < C_min
q_min = q_near_n;
C_min = q_near_n.cost + cost(q_near_n, q_new);
end
end
% Rewire
for j = 1:length(near_inds)
q_near_n = nodes(near_inds(j));
if obstacle_free(q_new, q_near_n, obstacle_radius) && q_new.cost + cost(q_near_n, q_new) < q_near_n.cost
q_near_n.parent = length(nodes);
nodes(near_inds(j)) = q_near_n;
end
end
% Add to tree
q_new.cost = C_min;
q_new.parent = q_min;
nodes(end+1) = q_new;
% Check if goal reached
if norm(q_new.pos - goal_point) < goal_radius
goal_node = length(nodes);
break;
end
end
% Plotting
if mod(i, 100) == 0
plot(q_new.pos(1), q_new.pos(2), 'bo', 'MarkerSize', 5, 'MarkerFaceColor', 'b')
plot([q_near.pos(1), q_new.pos(1)], [q_near.pos(2), q_new.pos(2)], 'b')
pause(0.01)
end
end
% Find path
path = [goal_point];
while true
curr_node = nodes(goal_node);
path = [curr_node.pos; path];
goal_node = curr_node.parent;
if goal_node == 1
path = [start_point; path];
break;
end
end
% Plot path
plot(path(:,1), path(:,2), 'r', 'LineWidth', 2)
```
这段代码实现了RRT*算法来规划机器人在一个二维空间中的路径。请注意,该代码仅用于演示和学习目的,并不是一个完整的路径规划解决方案。
阅读全文