Creating a function (pathfinding algorithm)

2 次查看(过去 30 天)
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 个评论
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