How to load large number of files and perform looping through each file?

12 views (last 30 days)
I have 153 files stored in a directory with extension of .txt. I want to load each and every file in a script and perform a mathematical calculation using for loop.
Chris Martin
Chris Martin on 4 Oct 2017
Edited: Cedric Wannaz on 4 Oct 2017
The files name are like this
like this there are 153 files are there and I want to load them one by another and the file content is like below
FIRST GSM-2_2002274-2002304_0031_GRGS_0080_03v3.txt SHM CNES / GRGS 20161025
EARTH 0.3986004415E+15 0.6378136460E+07
SHM 80 80 1.00 fully normalized exclusive permanent tide
GRCOF2 0 0 0.100000000000E+01 0.000000000000E+00 0.0000E+00 0.0000E+00 19500101.0000 20500101.0000 nnnn
GRCOF2 1 0 -.115491468132E-09 0.000000000000E+00 1.1643E-15 0.0000E+00 19500101.0000 20500101.0000 ynyn
I am trying it but have no clue how to proceed thats why I posted this, I have little knowledge on computer programming Regards...

Sign in to comment.

Answers (2)

Image Analyst
Image Analyst on 24 Sep 2017
This is a FAQ, perhaps the most F of the FAQs that we see. So see the FAQ document on your question:
Image Analyst
Image Analyst on 25 Sep 2017
Several times in the past when I have given a link to the FAQ, or to Vision Bibliography to find an algorithm, instead of providing a turnkey solution with full source code, people have accused me of being rude, and basically say to shut up if all I do is to give them a link. I ignore them.
In the past some would refer them to "Let me Google that for you"
Kind of funny, though maybe a bit less so since they toned it down (removed the snarky "There, was that so hard?" comment).

Sign in to comment.

Cedric Wannaz
Cedric Wannaz on 4 Oct 2017
You can use the output of DIR to produce a struct array of file names/folders and iterate through files:
D = dir( '*.txt' ) ;
for fileId = 1 : numel( D )
% Do something with D(fileId).name.
and then there are many functions (TEXTSCAN, IMPORTDATA, READTABLE, etc) for reading/parsing the content of text files when the structure seems to be a regular table/array with 3 rows of header.
If you need data from the header, you can use e.g. pattern matching through REGEXP.
Train on a single file, and when you understand how that work try to integrate it in the loop. Here I created a file named based on your example, and I filed it with the slice of content that you provided.
>> content = fileread( 'GSM-2_2002244-2002273_0030_GRGS_0080_03v3.txt' ) ;
>> earthParams = str2double( regexp( content, 'EARTH (\S+) (\S+)', 'tokens', 'once' )) ;
with that you get:
>> earthParams(1)
ans =
>> earthParams(2)
ans =
>> data = textscan( content, '%s%d%d%f%f%f%f%f%f%s', 'HeaderLines', 3, 'CollectOutput', true ) ;
and I let you look at what data contains.

Community Treasure Hunt

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

Start Hunting!