Simply for academic purposes, we can take a look at using recursion combined with conv
. This is inspired by both Luis Mendo's and Amit's approach.
In other words:
function [final] = convertNum(x)
function [out] = helper(in)
if numel(in) == 2
out = in;
else
out = helper(conv(in, [1 1], 'valid'));
end
end
digits = dec2base(x, 10) - '0';
final_digits = helper(digits);
final = str2num(sprintf('%i',final_digits));
end
convertNum
is the function we will use to take in a number and the output will be a two element vector that produces the sum of pair-wise elements at each step until there are two elements left.
We need a helper function that will take in an array of coefficients where this array consists of the extracted individual digits of the input number into convertNum
, which is stored in x
. What we do first is take our number x
and convert the digits into individual numbers (taken from thewaywewalk, Luis Mendo and Amit). Next, we call the helper function to compute our pair-wise sum.
The helper function operates in such a way where if we have an input number whose length is not equal to 2, we perform the pair-wise sum via conv
and use this to recurse into our helper function. Once the input consists of only two elements, this is what we return from the helper function, we take these two vectors and combine them into a single number. This is what we finally return to the user.
As such, working with x = 21020
, we get:
final = convertNum(21020)
final =
77
Similarly:
final = convertNum(4237)
final =
1115