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

1 visualizzazione (ultimi 30 giorni)
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.

Risposte (1)

Walter Roberson
Walter Roberson il 20 Ott 2017
  1 Commento
amateurintraining
amateurintraining il 20 Ott 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

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by