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

1 次查看(过去 30 天)
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.

采纳的回答

Image Analyst
Image Analyst 2014-7-10
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 个评论
Daniel Barzegar
Daniel Barzegar 2014-7-10
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 2014-7-10
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)

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Cell Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by