解释这行代码: %step3.扩展得到新节点 Pnear = [T.v(minInd).x,T.v(minInd).y]; Pvec = [Prand(1) - Pnear(1),Prand(2) - Pnear(2)]; Pvec = Pvec/norm(Pvec); Pnew = Pnear+step*Pvec; tmp_cost = T.v(minInd).cost + step; % disp('befor check!'); %step4.检查是否碰撞 if iscollision1(Pnear,Pnew,Pvec,Imp) continue; end % disp('after check!'); %step5.父节点重选择,在给定半径里面选择父节dian for i = i:size(T.v,2) dist = sqrt((Pnew(1) - T.v(i).x)^2 + (Pnew(2) - T.v(i).y)^2); if dist <= r %处理在给定园范围里面的 this_cost = dist + T.v(i).cost; if this_cost < tmp_cost %判断是否有障碍物 this_p = [T.v(i).x,T.v(i).y]; if iscollision2(this_p,Pnew,dist,Imp) continue; end tmp_cost = this_cost; minInd = i; end end end
时间: 2024-04-28 07:20:59 浏览: 10
这段代码是一个基于RRT(Rapidly-exploring Random Tree)算法的路径规划算法中的一部分,用于扩展树的节点,并检查新节点是否与障碍物相交。
具体来说,这段代码实现了以下几个步骤:
1. 从树的节点中选择一个最近的节点Pnear。
2. 生成一个随机点Prand,并计算出从Pnear到Prand的向量Pvec,并将其归一化。
3. 根据步长step,计算出新节点Pnew的坐标,即Pnear + step*Pvec。
4. 检查从Pnear到Pnew的路径是否与障碍物相交,若相交则跳过此次循环。
5. 在树中给定半径r内查找父节点,如果在这个半径内存在节点,则计算该节点到Pnew的距离,如果小于r,则将该节点作为Pnew的父节点,并更新该节点的代价cost。同时,如果从该节点到Pnew的路径与障碍物相交,则跳过此次循环。
这段代码的最终目的是扩展树的节点,寻找一条从起点到终点的路径,并避免路径与障碍物相交。
相关问题
优化这行代码: %step5.父节点重选择,在给定半径里面选择父节dian for i = i:size(T.v,2) dist = sqrt((Pnew(1) - T.v(i).x)^2 + (Pnew(2) - T.v(i).y)^2); if dist <= r %处理在给定园范围里面的 this_cost = dist + T.v(i).cost; if this_cost < tmp_cost %判断是否有障碍物 this_p = [T.v(i).x,T.v(i).y]; if iscollision2(this_p,Pnew,dist,Img) continue; end tmp_cost = this_cost; minInd = i; end end end
同样可以使用向量化运算,将循环改为矩阵运算:
dis = sqrt((Pnew(1) - [T.v(:).x]').^2 + (Pnew(2) - [T.v(:).y]').^2);
valid_ind = find(dis <= r);
for i = valid_ind
this_cost = dis(i) + T.v(i).cost;
if this_cost < tmp_cost
this_p = [T.v(i).x,T.v(i).y];
if iscollision2(this_p,Pnew,dis(i),Img)
continue;
end
tmp_cost = this_cost;
minInd = i;
end
end
这样可以使代码更加简洁高效。
优化这行代码: %step7.重连接,以Pnew为父节点 for i = i:size(T.v,2)-1 dist = sqrt((Pnew(1) - T.v(i).x)^2 + (Pnew(2) - T.v(i).y)^2); if dist < r && i ~= minInd %计算当前点经过Pnew的代价,如果更小就更新 this_cost = dist + tmp_cost; if this_cost < T.v(i).cost %如果没有发生碰撞 this_p = [T.v(i).x,T.v(i).y]; if iscollision2(this_p,Pnew,dist,Img) continue; end T.v(i).cost = this_cost; T.v(i).xPre = Pnew(1); T.v(i).yPre = Pnew(2); T.v(i).indPre = k; end end end
同样可以使用向量化运算,将循环改为矩阵运算:
dis = sqrt((Pnew(1) - [T.v(:).x]').^2 + (Pnew(2) - [T.v(:).y]').^2);
valid_ind = find(dis < r & (1:length(T.v) ~= minInd));
for i = valid_ind
this_cost = dis(i) + tmp_cost;
if this_cost < T.v(i).cost
this_p = [T.v(i).x,T.v(i).y];
if iscollision2(this_p,Pnew,dis(i),Img)
continue;
end
T.v(i).cost = this_cost;
T.v(i).xPre = Pnew(1);
T.v(i).yPre = Pnew(2);
T.v(i).indPre = k;
end
end
这样可以使代码更加简洁高效。