资源描述:
《A星算法matlab源码及详细注释》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、A星算法matlab源码及详细注释functionastardemo%ASTARDEMODemonstrationofASTARalgorithm%%CopyrightBobL.Sturm,Ph.D.,AssistantProfessor%DepartmentofArchitecture,DesignandMediaTechnology%formerlyMedialogy%AalborgUniversityiBallerup%formerlyAalborgUniversityCopenhagen%$Revision:0.1$$Date:2011Jan.1518h24:24
2、$n=20;%fieldsizenxntiles20*20的界面wallpercent=0.45;%thispercentoffieldiswalls45%的界面作为阻碍物(墙)%createthenxnFIELDwithwallpercentwallscontainingmovementcosts,%astartingpositionSTARTPOSIND,agoalpositionGOALPOSIND,thecosts%AstarwillcomputemovementcostforeachtileCOSTCHART,%andamatrixinwhichtostoret
3、hepointersFIELDPOINTERS[field,startposind,goalposind,costchart,fieldpointers]=...initializeField(n,wallpercent);%初始化界面%initializetheOPENandCLOSEDsetsandtheircostssetOpen=[startposind];setOpenCosts=[0];setOpenHeuristics=[Inf];setClosed=[];setClosedCosts=[];movementdirections={'R',&
4、#39;L','D','U'};%keeptrackofthenumberofiterationstoexitgracefullyifnosolutioncounterIterations=1;%createfiguresowecanwitnessthemagicaxishandle=createFigure(field,costchart,startposind,goalposind);%aslongaswehavenotfoundthegoalorrunoutofspacestoexplorewhile~max(ismember
5、(setOpen,goalposind))&&~isempty(setOpen)%ismember(A,B)返回与A同大小的矩阵,其中元素1表示A中相应位置的元素在B中也出现,0则是没有出现%fortheelementinOPENwiththesmallestcost[temp,ii]=min(setOpenCosts+setOpenHeuristics);%从OPEN表中选择花费最低的点temp,ii是其下标(也就是标号索引)%findcostsandheuristicofmovingtoneighborspacestogoal%inorder'
6、R','L','D','U'[costs,heuristics,posinds]=findFValue(setOpen(ii),setOpenCosts(ii),...field,goalposind,'euclidean');%扩展temp的四个方向点,获得其坐标posinds,各个方向点的实际代价costs,启发代价heuristics%putnodeinCLOSEDandrecorditscostsetClosed=[setClosed;setOpen(ii)];%将temp插入CLOSE表中s
7、etClosedCosts=[setClosedCosts;setOpenCosts(ii)];%将temp的花费计入ClosedCosts%updateOPENandtheirassociatedcosts更新OPEN表分为三种情况if(ii>1&&ii<length(setOpen))%temp在OPEN表的中间,删除tempsetOpen=[setOpen(1:ii-1);setOpen(ii+1:end)];setOpenCosts=[setOpenCosts(1:ii-1);setOpen