How do I turn the for function into a recursive function?

1 次查看(过去 30 天)
I have a function:
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)
filled=blank;
[a,b]=size(blank);
for f=1:1000
for x=2:a
for y=2:b
filled(x,y);
if filled(x,y)==0
if (filled(x-1,y)==f||filled(x+1,y)==f||filled(x,y-1)==f||filled(x,y+1)==f)
filled(x,y)=f+1;
end
else
filled(x,y);
end
end
end
end
But I don't know how to turn it into a recursive function.
I have tried the following:
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)
filled=blank;
[a,b]=size(blank);
for f=1:1000
for x=2:a
for y=2:b
filled(x,y);
if filled(x,y)==0
if (filled(x-1,y)==f||filled(x+1,y)==f||filled(x,y-1)==f||filled(x,y+1)==f)
filled(x,y)=travelDistance(filled(x,y)+1);
end
else
filled(x,y);
end
end
end
end
But it does not produce the correct product.

回答(1 个)

Walter Roberson
Walter Roberson 2017-10-20
  1 个评论
amateurintraining
amateurintraining 2017-10-20
I have attempted to edit my function, using a subfunction with the recursion made with your answer. I am still a little confused on the method but it produces an infinite recursion. Here is the new function:
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)
filled=blank;
[a,b]=size(blank);
for f=1:1000
for x=2:a
for y=2:b
filled(x,y);
if filled(x,y)==0
if (filled(x-1,y)==f||filled(x+1,y)==f||filled(x,y-1)==f||filled(x,y+1)==f)
filled(x,y)=helper(f,1,f,x,y);
end
else
filled(x,y);
end
end
end
end
end
function filled = helper(initial,increment,final,x,y)
filled=helper(initial+increment,increment,final,x,y);
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by