2d arry sorting
Show older comments
i have 2d array which consist of
- ). 1st row for y axis coordinate of point(i)
- ). 2nd row for x axis coordinate of point(i)
- ). ilet consider following
a(1,:)=[1,2,3,4,10,11,12,13,19,20,21,22];
a(2,:)=[4,1,3,2,4,3,1,2,3,2,4,1];
a(3,:)=[1,2,3,4,5,6,7,8,9,10,11,12];
according to the above array 'a' it shows that it is shorted according to the first column(according to y coordinates).
but in my case i want to sort them with following steps
- identify the position where the difference between two consecutive values of y coordinates (values of a(a,:)) changes rapidly and
- sort the values between those rapidly change with respect to x coordination (a(2,:))
let consider the following
a =
1 2 3 4 10 11 12 13 19 20 21 22
4 1 3 2 4 3 1 2 3 2 4 1
1 2 3 4 5 6 7 8 9 10 11 12
0 1 1 1 6 1 1 1 6 1 1 1
here 4th row represent the difference between two consecutive y coordinates (a(1,:))
in there 5th value shows rapid change so i want consider first 4 value set and analyze the x and y coordinates w.r.t x coordinate (a(2,:))
in same way for whole array and following array represented the expected results.
a =
2 4 3 1 12 13 11 10 22 20 19 21
1 2 3 4 1 2 3 4 1 2 3 4
1 2 3 4 5 6 7 8 9 10 11 12
0 1 1 1 6 1 1 1 6 1 1 1
note by:
the 3rd column value should not be changed.
the rapid changed is not obtained in same period like in above it varying.(in my case it happened after every 4 values )
the rapid change is not 6 for every instant (let the solution should convenience for values greater than 3)
- can any one help me to code this*
1 Comment
Sahan Priyanga
on 19 Nov 2015
Accepted Answer
More Answers (1)
Guillaume
on 18 Nov 2015
Here's how I'd do it:
a = [1 2 3 4 10 11 12 13 19 20 21 22
4 1 3 2 4 3 1 2 3 2 4 1
1 2 3 4 5 6 7 8 9 10 11 12];
splitlength = diff([0 find(diff(a(1, :)) >= 3) size(a,2)]); %find distance between rapid changes
splita = mat2cell(a([1 2], :), 2, splitlength); %split 1st two rows of into sub matrices
sortedsplita = cellfun(@(m) sortrows(m', 2)', splita, 'UniformOutput', false); %sort submatrices by second row
sorteda = [cell2mat(sortedsplita); a(3, :)] %recombine submatrices and 3rd row of a
Vectorised code, so should be fast.
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!