how to extract data from an text file?
이전 댓글 표시
I have two files, one in excel and one in a text file, how would i obtain column data from the text file even though i did it from an excel file.
code is:
filename = 'mct.xlsx'
data = xlsread(filename, 'mct', 'A:D');
Phase1 = data(data(:4)==1,:);
how would i be able to extract this from a text file?
채택된 답변
추가 답변 (3개)
fred ssemwogerere
2020년 2월 4일
% what does the 'w' mean?
'w' gives write access permission to the file
% also, what does ''%4.4f\n'' mean?
This is a formatting operator that prints each input as a fixed point number having field width of 4, and the number of digits after the decimal point of 4, before proceeding to a new line ("\n").
댓글 수: 8
isamh
2020년 2월 4일
Walter Roberson
2020년 2월 4일
dlmwrite('MCT_Drive_Traces.txt', x, 'delimiter', ' ', 'precision', 4)
You might possible prefer 'delimiter', '\t' for tabs between columns.
isamh
2020년 2월 4일
Walter Roberson
2020년 2월 5일
You have space tab for delimiter; it looks like you need '\t'
Phase_1 = dlmwrite(dlmwrite(:,4)==1,:);
??? You are trying to call the function dlmwrite() passing in a colon as the first parameter ??
dlmwrite('Phase_1.txt', x(x(:,4)==1,:), 'delimiter', 't', 'precision', 4)
Walter Roberson
2020년 2월 5일
delimiter '\t' not 't'
Walter Roberson
2020년 2월 5일
Sometimes you can use textscan CommentStyle to ignore headers if they always have the same start and stop. Otherwise sometimes you end up looping textscan, especially if you want the blocks to be separated in output.
Another method that can be very useful is to fileread() the entire file as a character vector, and then use a combination of regexp and regexprep to extract parts of it, possibly then passing the resulting characters into textscan.
댓글 수: 3
Walter Roberson
2020년 2월 12일
fgetl returns something that is not a character when it reaches end of file.
fgetl can return empty if the only thing on a line is the line terminator.
if isempty(tline); continue; end
isamh
2020년 2월 14일
Walter Roberson
2020년 2월 14일
result = [];
fid=fopen('MCT_Data.txt');
tic
while 1
tline = fgetl(fid);
if ~ischar(tline); break; end %end of file
if isempty(tline); continue; end %empty line
celldata = textscan(tline,'%f %f %f %f %f %f');
matdata = cell2mat(celldata);
% match fails for text lines, textscan returns empty cells
result = [result ; matdata];
end
toc
fclose(fid);
What is your file format? It appears that you have text at the beginning of some of the lines, and you are doing this looping so that you can ignore those lines? There are usually easier ways to deal with such files.
카테고리
도움말 센터 및 File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!