필터 지우기
필터 지우기

How do I read in a text file and sort it by a column

조회 수: 2 (최근 30일)
Aaron
Aaron 2013년 10월 10일
댓글: sixwwwwww 2013년 10월 12일
I have a file which I am trying to read and then sort by column A and then by column C. The text file is attached and has 3 columns. This is what I have tried but it will not let me use the sort function after reading it in this way:
function data = ResultsScript(filename)
fid = fopen(filename);
data = textscan(fid, '%s %f %f');
fclose(fid);
end
Then I call this function and try to sort it using:
fileName = 'Example.txt';
A = ResultsScript(fileName);
sortrows(A,[1,3]);
Running this gives the following error message:
??? Index exceeds matrix dimensions.
Error in ==> sortrows>sort_cell_back_to_front at 133
ndx = ndx(ind);
Error in ==> sortrows at 90
ndx = sort_cell_back_to_front(x_sub, col);
Error in ==> GetResults at 3
sortrows(A,[1,3]);
Any help is greatly appreciated.
  댓글 수: 2
sixwwwwww
sixwwwwww 2013년 10월 10일
The attachment is missing. Please attach file again
Aaron
Aaron 2013년 10월 12일
Sorry, now it should be attached.

댓글을 달려면 로그인하십시오.

채택된 답변

sixwwwwww
sixwwwwww 2013년 10월 12일
Dear Aaron, the problem here is that function "textscan" output data in the form of cell array which you must convert first into a matrix before using "sortrows" function because "sortrows" only accept vector or matrix data. So after converting it to proper form you can apply "sortrows". Also don't use "%s" to read values of double type instead use "%f" or better "%n". Following is the corrected code for this purpose:
fid = fopen(filename);
cell_data = textscan(fid, '%n %n %n');
fclose(fid);
matrix_data = [cell_data{:}];
After this you can apply:
sorted_data = sortrows(matrix_data, [1 3]);
  댓글 수: 2
Aaron
Aaron 2013년 10월 12일
Thank you very much for you help! And the first column of data isn't actually a double, it is a hexadecimal number. An EPC from a RFID tag.
sixwwwwww
sixwwwwww 2013년 10월 12일
You are welcome and sorry for misunderstanding about EPC because I don't know about EPC.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by