1

I have an array A having x and y values.. e,g.

A = 
    5  1
    7  2
    3  1
    5  3
    4  4
    7  3
    2  5
    9  5
    7  6

I need to take three values at one time and sort them in ascending order according to the x values (First 3 x y values Then next 3 x y values and so on. )

I want it in this order -

3  1
5  1
7  2
4  4
5  3
7  3
2  5
7  6
9  5

Can somebody suggest me a MATLAB code to get the required result?

Thank You

Divakar
  • 218,885
  • 19
  • 262
  • 358
Agror
  • 37
  • 9
  • @Shahbaz you must try solve it yourself first and tell us where you got stuck or at least what you've tried so far. – Dan Oct 21 '14 at 12:25
  • @Dan I am dealing with pixel coordinates and so far arranged the values in ascending order according to y values. I am stucked in the algorithm how can i select just 3 at one time sort them and move on. – Agror Oct 21 '14 at 12:27
  • 1
    @Shahbaz have you tried using a loop? Also you can select three items like this: `A(4:6)` or if you're looping on a variable like `for x = 1:3:size(A,1)` then `A(x:(x+2))` – Dan Oct 21 '14 at 12:38

1 Answers1

5

See if this works for you -

N = 3; %// group-size
[~,ind] = sort(reshape(A(:,1),N,[])) %// get sorted indices for the x values as 
                                     %// groups of N elements
Aout = A(bsxfun(@plus,ind,[0:(size(A,1)/N)-1]*N),:) %// get sorted indices for all
%// x values as a whole and use them to index into rows of A to get the desired output

Of course it assumes that the number of rows is divisible by N.

Divakar
  • 218,885
  • 19
  • 262
  • 358