Sum of Digits

8 次查看(过去 30 天)
joseph Frank
joseph Frank 2011-4-16
Hi,
If I have the following vector: [1 9 11 3 7 8 14] then how can I add the double digits (when the number is greater than 9)to get a single digit? i.e. to get: [1 9 2 3 7 8 5]

采纳的回答

Paulo Silva
Paulo Silva 2011-4-16
a=[1 9 11 3 7 8 14]
a(a>9)=a(a>9)-9
Edit: Like John said the code fails for numbers bigger than 18 and we can repeat the process, the following code works for every number but it will be slow for bigger values and vectors.
while max(a)>9
a(a>9)=a(a>9)-9
end
  2 个评论
John D'Errico
John D'Errico 2011-4-16
While this does work for numbers no larger than 18, it will fail for all larger values! The answer suggested does not compute the sum of the digits. It merely subtracts 9 from the number. For example, 22 will map to 13, which is still greater than 1. Yes, you can repeat the operation until the result is no larger than 9, but that seems a bit of a kludge, since it will take a long time for termination if a single element was as large as perhaps 123432455243.
Paulo Silva
Paulo Silva 2011-4-16
nice point John, I just tried to find the simplest way to satisfy the example provided

请先登录,再进行评论。

更多回答(1 个)

John D'Errico
John D'Errico 2011-4-16
A few better solution than Paulo's is to use modular arithmetic. This is because Paulo's solution fails for inputs larger than 18. Yes, you could simply repeat that process, but it would get time consuming if the element was 34343454356. In effect, you are performing division by repeated subtraction, a VERY slow operation for large inputs.
Instead, reduce your vector modulo 9, replacing any elements which got mapped to zero, with a 9.
vector = [1 9 11 3 7 8 14 197 90];
newvector = mod(vector,9);
newvector(newvector == 0) = 9;
In the event that any element in the original vector was already a 0, you may choose not to convert that 0 element to a 9. This would be a simple modification to the above code, so perhaps you would have done it as...
vector = [1 9 11 3 7 8 14 197 90];
newvector = mod(vector,9);
newvector((newvector == 0) & (vector ~= 0)) = 9;

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by