Clear Filters
Clear Filters

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

1 view (last 30 days)
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.

Answers (1)

Walter Roberson
Walter Roberson on 20 Oct 2017
  1 Comment
amateurintraining
amateurintraining on 20 Oct 2017
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

Sign in to comment.

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!