Sum of Digits

조회 수: 7 (최근 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;
  댓글 수: 1
Paulo Silva
Paulo Silva 2011년 4월 16일
+1 vote

댓글을 달려면 로그인하십시오.

카테고리

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