Open multiple text files remove all rows with number less than -65.0 in the first column

조회 수: 1 (최근 30일)
I have a folder with ~90 text files. For each text file I need to remove all rows that contain a number that is less than -65.0 in the first column.
For example these are my text files now are like this:
-300.0000 -60.0000 0.0000 29242
-299.9750 -60.0000 0.0000 29242
-70.9500 -60.0000 0.0000 29242
-66.9250 -60.0000 0.0000 29242
-65.0000 -60.0000 0.0000 29242
-29.8750 -60.0000 0.0000 29242
738.4500 -60.0000 0.0000 29242
738.4750 -60.0000 0.0000 29242
and this is what they need to be like:
-65.0000 -60.0000 0.0000 29242
-29.8750 -60.0000 0.0000 29242
738.4500 -60.0000 0.0000 29242
738.4750 -60.0000 0.0000 29242
I am new to matlab and here is what I have pieced together from what I have seen online but I cannot get it to work:
path='C:\Users\batti\Desktop\SimiFlex42\Exports\Topo';
files=dir(fullfile(path));
for k=1:length(files)
fid=fopen(fullfile(path,files(k).name));
datanew=fid(fid(:,1) >=-65.0,:);
fclose(datanew)
end
Any help would be appreciated

답변 (1개)

dpb
dpb 2018년 7월 20일
편집: dpb 2018년 7월 21일
A reasonable start with a few "issues"...
First, by just using dir you'll get the null directory entries as well as files, if you want all the files and they are .txt, use the wild card to get only files back...presuming, of course, you don't name folders with a '.txt' extension! :)
After that, fopen does not return any data; it only gives you a file handle for functions like textscan or fscanf to actually read the file. However, with a plain text file, there are higher-level functions that will read the file directly from the file name to even dispense with it... dlmread or importdata are two (altho the latter calls the former)...
path='C:\Users\batti\Desktop\SimiFlex42\Exports\Topo';
files=dir(fullfile(path,'*.txt')); % get .txt files only
for k=1:length(files)
data=dlmread(files(i).name; % read the file into array
data=data(data(:,1)>=-65.0,:); % keep that which is wanted
dlmwrite('file.txt',data,'delimiter',' ','precision','%10.4f')
end
The above will concatenate all data into one long file; if you need to keep them separated, then create a new file name in the loop based on the existing or some other name convention.

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by