How to read all text files in a folder with unknown number of files?

4 ビュー (過去 30 日間)
Chamath Vithanawasam
Chamath Vithanawasam 2018 年 7 月 26 日
編集済み: Benjamin Kraus 2018 年 7 月 27 日
I have an unknown number of text files that need to be read and put into tables, and then all of those tables need to be combined to 1 table and plotted in a GUI created in Matlab's GUIDE. I have attached two such text files.
I previously found out that in order to collect the data from each of these files, I would have to run the following code.
Day1 = 'SI010218.log';
opts = detectImportOptions(Day1);
opts = setvartype(opts,1,'datetime');
opts = setvaropts(opts,1,'InputFormat','dd.MM.uuuu HH:mm:ss');
table1 = readtable(Day1,opts);
Which would save that text file's data into a table named table1. I think I should add this to the
_OpeningFcn(
in the GUIDE.
Thing is, how do I let the code scan through an entire folder and read all the tables in it, and combine it all into one table?

採用された回答

Benjamin Kraus
Benjamin Kraus 2018 年 7 月 26 日
編集済み: Benjamin Kraus 2018 年 7 月 27 日
You can use the dir command to generate a list of files that match a specific pattern. Once you've done that, can you loop over the list of files and run the code block you pasted, except with the Day1 variable replaced by the file name. Then you need to concatenate the tables.
It might look something like this:
f = dir('*.log');
alldatatable = [];
for ii = 1:numel(f)
DayFile = f(ii).name;
opts = detectImportOptions(DayFile);
opts = setvartype(opts,1,'datetime');
opts = setvaropts(opts,1,'InputFormat','dd.MM.uuuu HH:mm:ss');
table1 = readtable(DayFile,opts);
if isempty(alldatatable)
alldatatable = table1;
else
alldatatable = [alldatatable; table1];
end
end
You may need to modify how the tables are joined, and you can probably consolidate some of the other code (such as detectImportOptions) if the files are all the same format, but this is the general approach to consider.
  2 件のコメント
Chamath Vithanawasam
Chamath Vithanawasam 2018 年 7 月 27 日
This does work, after I replace 'DayData' at line 8 with 'DayFile'. Was that a mistake? Because 'DayData' was not declared.
Benjamin Kraus
Benjamin Kraus 2018 年 7 月 27 日
Yes, that was a mistake. I've updated the code. Glad you got it working.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMigrate GUIDE Apps についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by