Sum of Digits
Show older comments
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]
Accepted Answer
More Answers (1)
John D'Errico
on 16 Apr 2011
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;
1 Comment
Paulo Silva
on 16 Apr 2011
+1 vote
Categories
Find more on Creating and Concatenating Matrices 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!