How to load large number of files and perform looping through each file?
조회 수: 5 (최근 30일)
이전 댓글 표시
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.
댓글 수: 5
답변 (2개)
Image Analyst
2017년 9월 24일
This is a FAQ, perhaps the most F of the FAQs that we see. So see the FAQ document on your question:
댓글 수: 4
Rik
2017년 9월 25일
I hope I don't need to clarify I don't mean to come across as arrogant, I'm genuinely surprised how you can find this forum, but not have the idea to Google the problem. Of course everyone has their own style of looking for a solution to a problem, but it seems so obvious to me that I just don't understand it.
Of course, for some problems it can be tricky to find the right keywords. I have spent many hours in frustrating searches to simple things for which I couldn't find the right keywords to search for. In my experience LaTeX is notorious for calling things just slightly different from what I would call them (similar to how new Matlab users sometimes confuse matrix and table).
Image Analyst
2017년 9월 25일
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.
Kind of funny, though maybe a bit less so since they toned it down (removed the snarky "There, was that so hard?" comment).
Cedric
2017년 10월 4일
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.
end
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 =
3.9860e+14
>> earthParams(2)
ans =
6.3781e+06
>> 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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!