How can I skip data while reading values from text file?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Muhammed Ali Fettahoglu
am 10 Jan. 2022
Kommentiert: Simon Chan
am 11 Jan. 2022
[z1, HH, TT,z2,z3,z4,z5,z6,z7,z8,z9] = textread('A.txt', '%f %f %f %f %f %f %f %f %f %f %f ' );
I am reading values from text file with this code. But before reading values, I have to delete the other parts with my hand. And I only want to read data when data's format like
899.0 997 13.2 6.2 63 6.65 170 16 295.2 314.8 296.4 this.
How can I skip the other parts in the text file which are not proper to read values?
I mean I need something like this,
if this row is not proper for my reading format, skip this row and continue to read from next row.
0 Kommentare
Akzeptierte Antwort
Simon Chan
am 10 Jan. 2022
I try to use function fgetl as follows:
Noticed that the first 2 rows have data format different from others, so they are removed from the following code.
fid = fopen('A.txt', 'rt');
tline = fgetl(fid);
Counter = 1;
while ischar(tline)
if ~isempty(str2num(tline))
rawdata{Counter,1} = tline; % Store the required data
Counter = Counter + 1;
end
tline = fgetl(fid);
end
fclose(fid);
value_in_cell = cellfun(@(x) str2num(x),rawdata,'uni',0); % Convert from string to number
length_in_cell = cellfun(@length,value_in_cell); % Calculate the number of data per row
idx = length_in_cell==11; % Index for row having 11 data
value = cell2mat(value_in_cell(idx)); % Convert from cell to matrix
3 Kommentare
Simon Chan
am 11 Jan. 2022
If the length of the data in a row are different, say 2,7,9 & 11 in your case, it is better to manipulate the numbers in a cell array (Variable value_in_cell in the above code).
Or you need to identify the locations of the missing data in each row and assign NaN into it.
The following modified code is going to put NaN for the first two rows after the existing numbers. Noticed that if the missing data is in the middle, then the following code doesn't work.
addlength = max(length_in_cell)-length_in_cell; % Calculate the difference in number of data vs max number
cellfun(@(x) [x,NaN(1,y)],value_in_cell,num2cell(addlength)) % Calculate how many NaN needs to add at the end of the data
samelength_in_cell = cellfun(@(x,y) [x,NaN(1,y)],value_in_cell,num2cell(addlength),'uni',0);% Add NaN to those data having less data
value = cell2mat(samelength_in_cell); % Convert to matrix
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Large Files and Big Data finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!