MATLAB Answers

Changing a for loop to recursion

16 views (last 30 days)
jacob Mitch
jacob Mitch on 10 Oct 2019
Commented: jacob Mitch on 11 Oct 2019
Just wondering if I could get a bit of help on this. How would I change this code to remove the for loop so it operates recursively.
function [x, y] = test(data)
c=1;
input=data;
x=length(input);
for z=2:x
if input(z-1)>input(z) && input(z)<input(z+1)
x(c,1)=z;
y(c,1)=input(z);
c=c+1
end
end
end
So far I have tried to change it and gotten
function [x, y] = test(data)
c=1;
input=data;
x=length(input);
if length(input(z-1))+2>length(input)
return
elseif input(z-1)>input(z) && input(z)<input(z+1)
x(c,1)=z;
y(c,1)=input(z);
c=c+1
end
end
end
But this just runs the if statement once and does not operate recursively.

Accepted Answer

David K.
David K. on 10 Oct 2019
Recursion happens when a function calls itself, which is something you are not doing.
The first step when creating a recursive function is to identify when the recursion stops. This is done by thinking about how will the function get smaller as you go. In this case, I think we can loop through each value by calling the function with one lessdata point. This means the function ends when the size of the input is less than 3, since we could no longer apply your algorithm.
Another important thing is we need to save what the index of the variable under consideration is so we need to pass the value of c into each new function. So I make the test1 function take c as an input as well and just say that if the function is called without c we set it to 2 to start the recursion.
Then we have your test but we always do it to the second element in the input array. Then we call our function again, increasing c by 1 and removing the first element of data.
Lastly we concatenate the results of the recursion to the results of the function and go back up.
function [x,y]=test1(data,c)
if nargin==1
c = 2;
end
input=data;
x = []; y = [];
if length(input)<3
return
else
if input(1)>input(2) && input(2)<input(3)
x = c;
y = input(2);
end
[xRecur, yRecur] = test1(input(2:end),c+1);
x = [x xRecur];
y = [y yRecur];
end
  3 Comments
jacob Mitch
jacob Mitch on 11 Oct 2019
Even better thank my fix. Thanks David!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!