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.
0 个评论
采纳的回答
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 个评论
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
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!