Sum down to one digit
조회 수: 4 (최근 30일)
이전 댓글 표시
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
채택된 답변
Jan
2018년 2월 2일
편집: Jan
2018년 2월 2일
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)
추가 답변 (5개)
Image Analyst
2018년 2월 1일
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
2018년 2월 1일
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
2018년 2월 1일
편집: Birdman
2018년 2월 1일
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
Jan
2018년 2월 2일
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
2018년 2월 1일
댓글 수: 11
Walter Roberson
2018년 2월 2일
Perhaps you should just take the number mod 9 (except using 9 instead of 0 for exact multiples): the results will be the same.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!