Turn my (easy) for loop into a recursive function?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Michael
le 15 Juil 2014
Commenté : Michael
le 15 Juil 2014
Hi all. I'm really stuck on this problem - probably simple for many people here. I'm given a number as an input. As my output, I just want a row vector of those digits. The code I have below works FINE and gives the desired result: say my input is N = 65479 and I run baseDigits(N).
function D = baseDigits(N)
D = zeros(1,length(num2str(N)));
for i = 1:length(num2str(N))
if N>0
D(i) = rem(N,10);
N = floor(N/10);
end
end
D = D(end:-1:1);
end
This gives me D = [6 5 4 7 9] as expected. The problem is, I'm supposed to use a while loop and make it a recursive function to do the same thing. It's supposed to be less than 10 lines long and it's supposed to be an easy problem... I just don't think it's 'clicked' on how recursive functions store intermediate values. I have something like:
function D = baseDigits(N)
if N<10
D = N
end
while N>=10
N = floor(N/10)
D = [baseDigits(N),rem(N,10)]
end
end
I'm not sure how to properly append the values or how they're stored in the meantime. Any help is greatly appreciated. Thanks! :)
0 commentaires
Réponse acceptée
Alfonso Nieto-Castanon
le 15 Juil 2014
Modifié(e) : Alfonso Nieto-Castanon
le 15 Juil 2014
You almost got it. Your are just: 1) overwriting the variable N, which you probably did not intend; and 2) including an unnecessary while loop, recursivity takes care of that:
function D = baseDigits(N)
if N<10
D = N;
else
M = floor(N/10);
D = [baseDigits(M),rem(N,10)];
end
end
EDIT: my guess is that the 'while loop' and the 'recursive function' are likely two separate requirements, because a recursive function for this problem that also includes a while loop seems awfully strange...
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!