Search code examples
matlaboctaveadditionrational-number

An efficient way to perform rational addition in GNU Octave / Matlab


Given F, an nx2 matrix of fractions ([num1, den1; num2, den2; ...]), how to efficiently compute the fraction that results from their addition? (i.e. [F(1,1)*F(2,2)*...*F(n,2) + F(1,2)*F(2,1)*F(2,3)*...*F(n,2) + ... , F(1,2)*...*F(n,2)]). The result doesn't have to be in irreducible form, the point is efficiency (meaning vectorized, not C code).


Solution

  • You can use arrayfun to apply a function to an array, and prod to take the product

    p = prod(F(:,2));
    G = arrayfun(@(x, y) x * p / y, F(:,1), F(:,2));
    

    Then your answer is

    [sum(G), p]
    

    or you can do it in a vectorized way as Divakar suggested as

    p = prod(F(:,2));
    G = F(:,1).*(p./F(:,2));
    [sum(G), p]
    

    I tested both on a 50x2 array with 1000 tries and the results were

    Elapsed time is 0.594867 seconds.
    Elapsed time is 0.012170 seconds.
    

    So indeed the vectorized way is much faster.