Creating a function (pathfinding algorithm)

조회 수: 2 (최근 30일)
amateurintraining
amateurintraining 2017년 10월 12일
댓글: amateurintraining 2017년 10월 12일
How do you create a function:
function [ filled ] = travelDistance ( blank )
where: blank is a two-dimensional array comprised of -1s, 0s and 1s, and filled is blank modified to the specifications below.
To create filled, replace every 0 in blank with its distance to the nearest 1 (staring at 2), traveling along cardinal directions (up, down, left and right) without passing through a -1 value. That is, all 0s that are directly next to a 1 should be changed to a 2 and all 0s next to any new 2s should be changed to 3s, and so on. Spaces with -1 values should be treated as “walls” and should stay -1. If there is no route from a 0 to a 1 without passing through a -1, it should remain a 0. The ultimate result should be that every 0 that is connected to a 1 is replaced with its distance to the nearest 1.
  댓글 수: 2
KSSV
KSSV 2017년 10월 12일
Okay..what you have attempted?
amateurintraining
amateurintraining 2017년 10월 12일
I tried doing this:
function [ filled ] = travelDistance( blank )
%TRAVELDISTANCE
% blank: two-dimensional array comprised of -1s, 0s, and 1s
% filled: blank that is modified (replace every 0 in blank with its
% distance to the nearest 1, tarting at 2, traveling along cardinal
% directions without passing through a -1 value)
function d = xyspace(A,x,y)
idx1=find(ismember(A,x));
idx2=find(ismember(A,y));
x=union(idx1,idx2);
whichset=ismember(x,idx1)+2*ismember(x,idx2);
idx=diff(whichset)>0;
d=x([false,idx])-x([idx,false]);
end
filled=xyspace(blank,0,1);
end
But this results in an error:
Error using horzcat
Dimensions of matrices being concatenated
are not consistent.
Error in travelDistance/xyspace (line 14)
d=x([false,idx])-x([idx,false]);
Error in travelDistance (line 17)
filled=xyspace(blank,0,1);
I think this error occurs because the function only works for a 1xn array.

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2017년 10월 12일
To do it that way (manually), then fist compute the distance transform with bwdist().
Otherwise, do it automatically with bwdistgeodesic(). See Steve's blog: http://blogs.mathworks.com/steve/2011/11/01/exploring-shortest-paths-part-1/

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by