Question

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?
Was it helpful?

Solution

You need to change the line

if Z(j)  + C(j+1) < 9

to

if Z(j)  + C(j+1) <= 9

Then it should work.

OTHER TIPS

You can take advantage of dec2base, str2num and num2str functions:

function StackOverflow
    x = [1 2 3];
    y = [4 5 6];

    numX = DigitsToNum(x);
    numY = DigitsToNum(y);

    digits = NumToDigits(numX+numY);
    disp(digits);
end

function digits = NumToDigits(x)
    digits = double( dec2base(x,10) - '0');
end

function num = DigitsToNum(x)
    st = strrep(num2str(x),' ','');
    num = str2num(st); %#ok<ST2NM>
end

Another way to implement the two functions above:

function digits = NumToDigits(x)
    digits = [];
    while x > 0
        digits(end+1) = mod(x,10); %#ok<AGROW>
        x = floor(x/10);
    end
end

function num = DigitsToNum(x)
    baseMult = power(10,0: (numel(x)-1));
    num = sum( baseMult.*x );
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top