MATLAB Answers

How to Add the Individual digits of a result ?

16 views (last 30 days)
Shravankumar P
Shravankumar P on 28 Jun 2014
Edited: Star Strider on 28 Jun 2014
>> 789*4567
ans =
3603363
I want to add each element of the ans :
i.e., >> 3+6+0+3+3+6+3
ans =
24
Help me how to do this?

  0 Comments

Sign in to comment.

Accepted Answer

dpb
dpb on 28 Jun 2014
Lots of ways...just a couple--
>> sum(str2num(num2str(789*4567).'))
ans =
24
>> >> sum(sscanf(num2str(789*4567),'%1d'))
ans =
24
>>

  0 Comments

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 28 Jun 2014
Try this:
theNumber = 3603363
theString = num2str(theNumber)
theSum = sum(theString - '0')
(I hope I didn't just do your homework.)

  0 Comments

Sign in to comment.

Categories