I have the following problem. Suppose I have to arrays X and Y whose entries consist of integers in the range 0 through 9 like
X = [1 2 3]
Y = [7 0 9]
I want to think of these arrays as being the digits of base-10 numbers, so X represents the number 123 and Y represents the number 709. I want to write a program which outputs the digits of the sum of these integers. So in the example given, it should output the array
Z = [8 3 2]
since 123 + 709 = 832. For the sake of this question it suffices to assume that X and Y have the same length, i.e., that the numbers they represent have the same number of digits. While I am doing this, I also want to keep track of carries which were performed during the addition. So in the example, I'd also want to output
C = [0 0 1]
which represents that I had to carry a 1 when I added the digits 9 + 3 = 12, but that the additions of the digits in other positions went through without carries. So my main question is
- Does anyone know of a simple way to achieve this goal using MATLAB?
So far, what I've come up with is the following code which is given the two numbers as X and Y
clear all; clc;
C = zeros(1, length(X));
for j=length(X):-1:1
if X(j) + Y(j) > 9
C(j) = 1;
end
Z(j) = mod(X(j) + Y(j), 10);
if j < length(X)
if Z(j) + C(j+1) < 9
Z(j) = Z(j) + C(j+1);
else
Z(j) = mod(Z(j) + C(j+1), 10);
C(j) = 1;
end
end
end
if C(1) == 1
Z = [1 Z];
end
Z
C
The problem is that the code only works sometimes. For example, it has no problem working through the example I gave above, that 123 + 709 = 832 with a "carry array" of [0 0 1]. But the input X = 52514 and Y = 41525 does not yield the correct results. So my follow up question is
- Does anyone see the bug in the code above/how can I fix it?