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 Center および File ExchangeShifting and Sorting Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by