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.
0 个评论
回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!