Changing a for loop to recursion
163 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
jacob Mitch
el 10 de Oct. de 2019
Comentada: jacob Mitch
el 11 de Oct. de 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.
0 comentarios
Respuesta aceptada
David K.
el 10 de Oct. de 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 comentarios
David K.
el 11 de Oct. de 2019
Yeah, it was because your loop when to the max size of input but you were still trying to check if input(z+1) was less than input(z) which would exceed indices. The reason this only happens sometimes is because Matlab does not evaluate the second part of an and statement if the first part was false. So when input(end)>input(end-1) it stops instead of trying to evaluate input(end+1) which does not work.
A likely simpler way to fix it is to just make the for loop
for z=2:x-1
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!