Sum down to one digit
3 views (last 30 days)
Show older comments
I am trying to Sum numbers in a matrix down to one digit.
I am using this code
>> tic,s=0; while num>=1, s=s+rem(num, 10); num = floor(num / 10); end,toc,s
Elapsed time is 0.000010 seconds.
s =
78
I don't know how code properly another loop into this code to sum down the sum.
Can someone help me find a solution and explain it, if possible?
Thanks for helping
4 Comments
Accepted Answer
Jan
on 2 Feb 2018
Edited: Jan
on 2 Feb 2018
num = 123456789;
while num > 9
dec = 10 .^ (0:ceil(log10(num)) - 1);
digits = rem(floor(num ./ dec), 10);
num = sum(digits);
end
disp(num)
The conversion from the number to the digits is done inside sprintf also, but this performs an additional conversion to a char vector. I prefer to stay at the original data type, although it is nice to hide the actual calculations inside the built-in sprintf.
I hope that this is not your homework. Otherwise it gets harder to submit your own version to avoid "cheating".
Based on your own method all you need is an additional outer loop:
num = 123456789;
while num > 9
s = 0;
while num >= 1
s = s + rem(num, 10);
num = floor(num / 10);
end
num = s;
end
disp(num)
More Answers (5)
Image Analyst
on 1 Feb 2018
Here's another way, using the string trick:
num = 123456789
digits = num2str(num) - '0';
s = 0;
for k = 1 : length(digits)
s = s + digits(k);
end
s % Print to command window
Walter Roberson
on 1 Feb 2018
There are numerous approaches. One of them is
while num > 9
break num up into last digits, and num without the last digit
replace num with the sum of that last digit and the number without the last digit
end
Using mod() to get the last digit is fine.
Birdman
on 1 Feb 2018
Edited: Birdman
on 1 Feb 2018
num=123456789;s=0;
while num>0
s=s+mod(s,10);
num=floor(num/10);
end
while numel(num2str(s))~=1
s=floor(s/10^(numel(num2str(s))-1))+mod(s,10^(numel(num2str(s))-1));
end
3 Comments
Jan
on 2 Feb 2018
Using numel(num2str(s)) is a very indirect way of s < 10 . numel(num2str(s)) could be expressed directly by floor(log10(s)) + 1. Even sprintf would have less overhead as num2str.
F K
on 1 Feb 2018
11 Comments
Walter Roberson
on 2 Feb 2018
Perhaps you should just take the number mod 9 (except using 9 instead of 0 for exact multiples): the results will be the same.
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!