MATLAB: Hi guys. I need help splitting a number into its individual parts and then add them. E.g. the number would be 1994 = 1 + 9 + 9 + 4 = 23

splitting numbers

I don't want the number to turn a scalar into an array eg x = 1994 = 1 9 9 4 I want it the scalar x = 1994 to split into multiple scalars. I hope this makes sense and your help will be much appreciated

Best Answer

When you say you do not want the number to turn to a scalar, I think what you are saying is you don't want to convert the scalar number x = 1994 into a vector v = [1 9 9 4].
If you are allowed to use string functions and are loose on your restriction, consider this:
x = 1994
%Convert x = 1994 to a vector of characters
a = num2str(x); %a now holds ['1' '9' '9' '4']
%Go through each of the elements in the vector, a, convert them to numbers and add them up
sum = 0;
for i = 1:size(a, 2)
sum = sum + str2num(a(i));
end
%sum now contains the sum of the individual digits
But this seems like a typical undergraduate homework problem :-) for a comp. sci./electrical enginering course :-) and the string approach above is unlikely to be the proper solution. I hope no one else provides the mathematical solution to this :-) as this is not a MATLAB question.
As a hint, consider the significance of the position of the individual digits in the number. We call them the one's, ten's, hundred's, and thousand's position for a reason :-)