1

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).

nightcod3r
  • 752
  • 1
  • 7
  • 26
  • For large multiplications your method might exceed the range of 2^52 which will result in inaccurate results.Maybe use `lcm` to get smaller values? – Daniel Apr 05 '16 at 09:39
  • 2
    If `F` is `nx2`, shouldn't that be `F(1,1)*F(2,2)*F(3,2)...*F(n,2) + F(2,1)*F(1,2)*F(3,2)...*F(n,2) + ... F(n,1)*F(1,2)*F(2,2)...*F(n-1,2)` instead? – Divakar Apr 05 '16 at 09:44
  • @Divakar Absolutely. Corrected. – nightcod3r Apr 05 '16 at 13:24

1 Answers1

3

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.

Sbte
  • 76
  • 1
  • 7
  • 5
    Or `F(:,1).*(prod(F(:,2),1)./F(:,2))` in a vectorized way. – Divakar Apr 05 '16 at 09:56
  • @Divakar This new point doesn't have the entity to raise a new question, so I'm giving it a try here: Having an index to F as an m x k matrix I, where F( I( :, j), : ) are the fractions to sum for each column of I. How to compute the sum of all the groups of m fractions in a vectorized way? [ prodfrac(F(I( :, 1), :)), ..., prodfrac(F(I( :, k), :)) ] (where prodfrac is the solution proposed above by Sbte) – nightcod3r Apr 05 '16 at 15:04
  • 1
    Something like this? `F1 = reshape(F(l,1), size(l,1), size(l,2)); F2 = reshape(F(l,2), size(l,1), size(l,2)); G = F1 ./ F2 * diag(prod(F2)); [sum(G)', prod(F2)']`. Note that `diag` here is probably slow so you might want to use `spdiags` instead. – Sbte Apr 05 '16 at 21:37