How can I sort my data by within a sorting

4 views (last 30 days)
John Hunt
John Hunt on 10 Oct 2017
Edited: dpb on 10 Oct 2017
I have a set of x,y,z data. I want to have all of the data sorted by x (least to greatest), then I want to have the y data be sorted within the x sort (least to greatest in the positive x data and then least to greatest for the negative data). I then want to do the same in the same for the z data in the positive and negative y data. How can I do that?
  1 Comment
John Hunt
John Hunt on 10 Oct 2017
The answers below are almost what I need, this sorts the data by the last column, so I have positive number with negative numbers in the -x numbers. I need them separate.
so -x,y -x,-y -x,-y -x,-y -x,y x,y x,-y x,-y x,y x,y to --> -x,-y -x,-y -x,-y -x,y -x,y x,-y x,-y x,y x,y x,y

Sign in to comment.

Answers (2)

Cedric Wannaz
Cedric Wannaz on 10 Oct 2017
[xyz_sorted, id] = sortrows( [x(:),y(:),z(:)] ) ;
dpb on 10 Oct 2017
Ewww...that's taking some doing but isn't too bad; just bookkeeping.
  1. sort x keeping index vector, iSrt
  2. get logical vector for y of negative locations, iNegY
  3. build sorted row in pieces of [x(iSrt(iNegY)) y(iNegY)]
  4. concatenate the remainder with [x(iSrt(~iNegY)) y(~iNegY)]
Is then complicated that there's the subsequent partitioning of Z as subset of Y to keep those pieces so in reality there's four subsections, not just two (or, of course, if you also mean this for X, then it's 8).
I've got another appointment at moment, but that's the idea...

Sign in to comment.

dpb on 10 Oct 2017
Edited: dpb on 10 Oct 2017
doc sortrows
Following up on previous note -- given
>> x=rand(10,1); y=rand(size(x))-0.5;
>> [x y]
ans =
0.1576 0.1557
0.9706 -0.4643
0.9572 0.3491
0.4854 0.4340
0.8003 0.1787
0.1419 0.2577
0.4218 0.2431
0.9157 -0.1078
0.7922 0.1555
0.9595 -0.3288
for the x,y case
>> [~,iSrt]=sort(x);
>> iNegY=y<0;
>> [sortrows([x(iSrt(iNegY)) y(iNegY)]); ...
sortrows([x(iSrt(~iNegY)) y(~iNegY)])]
ans =
0.1576 -0.4643
0.9572 -0.1078
0.9706 -0.3288
0.1419 0.1557
0.4218 0.3491
0.4854 0.4340
0.7922 0.1787
0.8003 0.2577
0.9157 0.2431
0.9595 0.1555
Presuming that's the desired result, have to subsequently partition z by the two subsections within y for total of four pieces.


Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by