how to use for loop ?

조회 수: 1 (최근 30일)
pruth
pruth 2017년 11월 24일
답변: pruth 2017년 11월 26일
one of my friend help me to write this code to read one text file which works perfect. but now I want to use this code to process multiple text files from one same folder. I am attaching 3 files for example. I am not able to use perfect loop for all these files.
content = fileread( 'L3_tropo_ozone_column_apr14.txt' ) ;
filename = char('L3_tropo_ozone_column_apr14.txt')
% - Remove first space on all data rows.
content = regexprep( content, '(?<=[\r\n]) ', '' ) ;
% - Split by "lat = ..." separator.
blocks = regexp( content, '\s+lat[^\r\n]+', 'split' ) ;
% - Extract header from block 1.
pos = regexp( blocks{1}, '\)\s+\d', 'start' ) ;
header = blocks{1}(1:pos) ;
blocks{1} = blocks{1}(pos+1:end) ;
% - Merge blocks, remove \r\n, replace spaces by 0s.
blocks = [blocks{:}] ;
blocks = regexprep( blocks, '[\r\n]', '' ) ;
blocks(blocks == ' ') = '0' ;
% - Convert to 120x288 numeric array.
data = reshape( sscanf( blocks, '%3d' ), 288, 120 ).' ;

채택된 답변

pruth
pruth 2017년 11월 26일
finally I somehow I did
O3_data_folder = 'C:\Users\Myself\Dropbox\prithvi_project\o-3';
cd(O3_data_folder);
%%open files in the data folder
temp = dir();
O3filenames = [];
%%%for the program to not read .files
flag_1 = 0 ;
for i = 1:numel(temp);
if (strncmp(temp(i).name, '.', 1) == 1);
flag_1 = flag_1 +1 ;
else
O3filenames{i-flag_1} = temp(i).name ;
end
end
for file = 1:size(O3filenames,2);
fname = char(O3filenames(file));
fid= fopen(fname(file)); % creating file id
content = fileread(fname) ;
% - Remove first space on all data rows.
content = regexprep( content, '(?<=[\r\n]) ', '' ) ;
% - Split by "lat = ..." separator.
blocks = regexp( content, '\s+lat[^\r\n]+', 'split' ) ;
% - Extract header from block 1.
.
.
.end

추가 답변 (1개)

KSSV
KSSV 2017년 11월 24일

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by