how to sort a matrix based on a specific value and bring the row at the beginning of the file

1 view (last 30 days)
Hi all, i want to do a strange sort into my file. I have a file which contains values like:
100 200 x1
201 340 x2
341 400 x4
405 460 x1
461 500 x5
501 600 x1
etc
I want in a way to search for the rows that in their 3rd column have the value x1 and then put the whole row at the beginning of the file. So as an output i d like to have something like:
100 200 x1
405 460 x1
501 600 x1
201 340 x2
341 400 x4
461 500 x5
any ideas? thanks in advance.

Accepted Answer

Image Analyst
Image Analyst on 10 Jul 2014
See if you can put a row at the beginning that's column names, like
c1, c2, c3
Is that a possibility? If so, it makes it easier since you can use readtable().
Then try readtable() to read it in
t=readtable(filename);
Then sort the third column. Extract the third column like
column3 = t.c3;
then see if you can use sort(). Take both outputs of sort. Use the sort order to sort the rows of the other columns. Is this homework? If not, attach your data file.
  3 Comments
Daniel Barzegar
Daniel Barzegar on 10 Jul 2014
Columnds 1 and 2 represent the start and end time of an instance respectively, whereas the 3rd column is the label. So, for example for the label 4 i want to bring all the start-end time rows at the beginning of the file.
i hope it's more clear now what i want to do.
Image Analyst
Image Analyst on 10 Jul 2014
OK, so column 3 actually is not "x1" or "x2" or any other strings, but it's actually a floating point number. In that case you can just use dlmread() and sortrows() (as Roger actually suggested before me):
filename = 'damyannotation.txt';
M = dlmread(filename)
sortedM = sortrows(M, 3)

Sign in to comment.

More Answers (1)

Roger Stafford
Roger Stafford on 10 Jul 2014
Edited: Roger Stafford on 10 Jul 2014
If you put that data in a single matrix M, the 'sortrows' function will do what you want:
M = sortrows(M,3);

Categories

Find more on Cell Arrays 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!