How do I import multiple files from a folder in MATLAB?

153 ビュー (過去 30 日間)
Samyukta Ramnath
Samyukta Ramnath 2013 年 6 月 10 日
I want to open all the files with a certain attribute (e.g. they all have 'History' in their name) and open them, one by one, in MATLAB. I know of the command dir my_name.txt which will list it like I want, but how do I now open the files that it listed?
  2 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 6 月 10 日
how do you want to open those files?
Samyukta Ramnath
Samyukta Ramnath 2013 年 6 月 10 日
I need to open them as in fopen The code that I tried was
if true
% code
matfiles = dir(fullfile('E:\MachineLearning\TestFiles\*.txt'));
data = cell(4,100);
for i = 3 : 7
fid = fopen(matfiles(i).name);
data{i} = fscanf(fid,'%c');
end
end
This worked but I need to know how to open only the files with a certain something in their name. For example open all files with '.txt' in the name. That is, open all text files only.

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

採用された回答

Walter Roberson
Walter Roberson 2013 年 6 月 10 日
編集済み: Walter Roberson 2013 年 6 月 10 日
Remember to fclose(fid) after you do the fscanf()
The code you show will already only locate file names ending in .txt .
You should be more careful with directories, though:
testfiledir = 'E:\MachineLearning\TestFiles\';
matfiles = dir(fullfile(testfiledir, '*.txt'));
nfiles = length(matfiles);
data = cell(nfiles);
for i = 1 : nfiles
fid = fopen( fullfile(testfiledir, matfiles(i).name) );
data{i} = fscanf(fid,'%c');
fclose(fid);
end
  2 件のコメント
Samyukta Ramnath
Samyukta Ramnath 2013 年 6 月 10 日
Ah yes, I could make the computer lose a lot of memory without fclosing! Thank you!
Walter Roberson
Walter Roberson 2013 年 6 月 10 日
It would probably run out of file descriptors before it ran out of memory.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by