Turn my (easy) for loop into a recursive function?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Alfonso Nieto-Castanon
2014-7-15
编辑:Alfonso Nieto-Castanon
2014-7-15
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...
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!