MATLAB: Sort 2 matrices for minimum numbers sum and divide them

MATLAB

I have r = [ 1 3 4 5 ……n]
and x = [ 5 8 9 4 ……n]
I will like to do this computation
when m = 1
sort the lowest number of r and divide it with the lowest number of x till the end n
for example =[ 1/4, 3/5, 4/8, 5/9…….n]
when m = 2
= [(1 + 3) / (5 + 4) , (4 +5)/(8+9) , ………..n]
when m =3
=[ (1 + 3 + 4)/( 4 + 5 + 8),…………….n]
Thanks for your help in advance
Tino

Best Answer

  • This is MATLAB, so don't waste your time writing inefficient loops.
    Learn to write simpler vectorized code, just like experienced MATLAB users do:
    >> r = sort([1,3,4,5,10]); % sorted!

    >> x = sort([5,8,9,4,10]); % sorted!
    >> m = 1;
    >> n = m*fix(numel(r)/m);
    >> sum(reshape(r(1:n),m,[]),1) ./ sum(reshape(x(1:n),m,[]),1)
    ans =
    0.25000 0.60000 0.50000 0.55556 1.00000
    >> m = 2;
    >> n = m*fix(numel(r)/m);
    >> sum(reshape(r(1:n),m,[]),1) ./ sum(reshape(x(1:n),m,[]),1)
    ans =
    0.44444 0.52941
    >> m = 3;
    >> n = m*fix(numel(r)/m);
    >> sum(reshape(r(1:n),m,[]),1) ./ sum(reshape(x(1:n),m,[]),1)
    ans =
    0.47059