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!