Sum of Digits
이전 댓글 표시
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]
채택된 답변
추가 답변 (1개)
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;
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!