필터 지우기
필터 지우기

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에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by