How do I turn the for function into a recursive function?
1 view (last 30 days)
Show older comments
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 Comments
Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!