# Addition of numbers in array as string

5 views (last 30 days)
Muhammad Usman on 15 Feb 2021
Commented: Walter Roberson on 16 Feb 2021
I am following these lines of code, but generating error when I do:
x = randi([0,9],1,20);
y = randi([0,9],1,20);
x_new = str2double(sprintf('%d',x));
y_new = str2double(sprintf('%d',y));
result = num2str(x_new+y_new) - '0';
fprintf('%4d',x);
fprintf('\n');
fprintf('%4d',y);
fprintf('\n');
disp('+');
disp('-------------------------------------------------------------------------')
fprintf('%d',result);
fprintf('\n')
The ouput I get (which is wrong):
9 6 1 3 0 5 4 9 8 4 8 1 3 9 9 7 6 3 9 1
7 6 8 3 7 8 3 5 9 5 3 6 3 7 4 4 6 9 3 8
+
-------------------------------------------------------------------------
1-272968385801777453-520
can someone please mention the mistake in running these lines. And help me to align (with same gap spaces) the result
the will be the addition of these numbers.
Thanks

Walter Roberson on 15 Feb 2021
double('1')
ans = 49
double('2')
ans = 50
'1' + '2'
ans = 99
char(ans)
ans = 'c'
MATLAB makes absolutely no attempt to recognize that if you add '1' + '2' that you might be wanting it to mean add 1 and 2.
char(('1' + '2') - '0')
ans = '3'
That works, but that isn't what you did.
num2str('1' + '2') - '0'
ans = 1×2
9 9
That's what you did. You got the printable representation of the sum and subtracted '0' from that, whereas what you needed was to subtract '0' from the sum.
But even then...
'3' + '8' - '0'
ans = 59
char(ans)
ans = ';'
When you do arithmetic on characters, you have to allow for overflow.
I suggest you subtract '0' from each of the characters, line the two up so that the right side matches and zero-pad on the left if need be. Now add, getting a vector of decimal values. Now run through the vector starting from the right, and each position that is 10 or greater, subtract 10 from that entry and add 1 to the entry to the left... watching out for a final carry that expanded the number of digits.
Once you have the vector of decimal values, having carried out the carries, add back '0' and convert to char()
Walter Roberson on 16 Feb 2021
Can you please modify my code as my code works so fine when a choose:
I already described what to do. You should revise your code nearly completely. I will not write this code for you, as you are doing a homework assignment.
I suggest you subtract '0' from each of the characters, line the two up so that the right side matches and zero-pad on the left if need be. Now add, getting a vector of decimal values. Now run through the vector starting from the right, and each position that is 10 or greater, subtract 10 from that entry and add 1 to the entry to the left... watching out for a final carry that expanded the number of digits.
Once you have the vector of decimal values, having carried out the carries, add back '0' and convert to char()