how to extract data from an text file?
159 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
isamh
am 3 Feb. 2020
Kommentiert: Walter Roberson
am 14 Feb. 2020
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?
0 Kommentare
Akzeptierte Antwort
fred ssemwogerere
am 3 Feb. 2020
Hello, there are a number of ways to go about this. Please refer to the following links:
1 Kommentar
Weitere Antworten (3)
fred ssemwogerere
am 4 Feb. 2020
% 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 Kommentare
Walter Roberson
am 5 Feb. 2020
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.
isamh
am 12 Feb. 2020
Bearbeitet: isamh
am 12 Feb. 2020
3 Kommentare
Walter Roberson
am 14 Feb. 2020
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.
Siehe auch
Kategorien
Mehr zu Text Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!