I'm not sure why you would want to replace your loop by a recursive function as it's often less efficient. It's certainly possible, you would call you recursive function with an array shorter by one element, with a carry at each step. Something like:
function res = singledigit(res)
res = recurse([0 res], 0);
end
function res = recurse(res, carry)
res(end) = res(end) + carry;
carry = floor(res/10);
res(end) = mod(res(end), 10);
if numel(res) > 1
res(1:end-1) = recurse(res(1:end-1), carry);
end
end
I don't see that as any better as your loop. What would be better however would be to vectorise the calculation. As you know that no value is never greater than 18, the carry will never be more than 1 and adding the carry before doing a modulus will never bring any value above 19. Thus the following is guaranteed to work:
res = mod([0 res] + [floor(res/10) 0], 10);
Best Answer