MATLAB: Reading image in zig zag, and arrange the output matrix in ascending and descending issue

digital image processingimage analysis

I am trying to image a figure and create G-code by reading the figure in zig-zag way. Thus, first I red the figure and dedect the edges and generate matrix for the edges.
The generated matrix like this:
AA =
[ 21 13
22 13
23 13
24 13
41 13
42 13
43 13
44 13
45 13
46 13
18 14
19 14
20 14
25 14
26 14
27 14
28 14
47 14
48 14
17 15
29 15
41 15
48 15
. . ], so on.
What I need to do to, arrange the first colume at coloume two value 13 by ascending way, and at second column value 14 by decending way and so on.
after that, I want to format these coordiantions in G-code format
How can I do this?
attached is an example for my code until and a figure sample

Best Answer

>> A = [5,13;7,13;6,13;4,14;5,14;8,14;5,16;8,16;7,16;9,16;3,20;6,20;8,20;9,20]
A =
5 13
7 13
6 13
4 14
5 14
8 14
5 16
8 16
7 16
9 16
3 20
6 20
8 20
9 20
>> B = sortrows(A,[2,1]);
>> X = ~mod(cumsum([true;diff(B(:,2))~=0]),2);
>> B(X,:) = sortrows(B(X,:),[2,-1])
B =
5 13
6 13
7 13
8 14
5 14
4 14
5 16
7 16
8 16
9 16
9 20
8 20
6 20
3 20