How to process multiple txt files in a loop?

I have multiple txt files in a folder, and I wrote a code to process a single file:
function output = do(input)
filename = ('c:\.....');
fileID = fopen(filename);
.....
process data
.....
output single output
fclose(fileID);
end
What is needed so that MATLAB processes all the files in the folder, and output all output into a single column matrix?
Much Thanks!

 採用された回答

George
George 2016 年 9 月 27 日

3 投票

Get an array of file names and loop over that array. e.g.,
files = ['file1.txt' 'file2.txt' 'file3.txt'];
for ii = 1:numel(files)
fid = fopen(files(ii))
...
fclose(fid)
end
or you can use datastore() with the location as a wildcard.

4 件のコメント

Terek Li
Terek Li 2016 年 9 月 27 日
But I got more than 100 files, not a good idea to list out all the file names.
George
George 2016 年 9 月 27 日
You don't have to type them all in. datastore will let you use a wildcard and dir will let you capture file names in a directory.
Nayani Ilangakoon
Nayani Ilangakoon 2016 年 11 月 7 日
Hi George, I tried to use datastore to get multiple files to process. Although it shows it has got all the files, I do not know how to pull out data from each file into separate tall arrays. Any help is highly appreciated.
George
George 2016 年 11 月 9 日
Datastore is probably not the best solution for that situation. It solves the opposite problem of "I don't care how many files my data is in, I want to aggregate it into a variable". Use dir to get the filenames.

サインインしてコメントする。

その他の回答 (1 件)

Massimo Zanetti
Massimo Zanetti 2016 年 9 月 27 日
編集済み: Massimo Zanetti 2016 年 9 月 27 日

3 投票

With DIR function you have access to all data in a folder. An example is
%provide the path to your folder as argument
MyFolderInfo = dir('C/...');
%the names of the files are:
%MyfolderInfo(1).name
%MyfolderInfo(2).name
%etc....
%for example you can run your function DO on each of them
for k=1:size(MyFolderInfo,1)
out{k} = do(MyFolderInfo(k).name);
end

カテゴリ

ヘルプ センター および File ExchangeFile Operations についてさらに検索

製品

タグ

質問済み:

2016 年 9 月 27 日

コメント済み:

2016 年 11 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by