Turn my (easy) for loop into a recursive function?
Afficher commentaires plus anciens
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! :)
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!