Read different files with different names (string) in a loop in MATLAB

5 ビュー (過去 30 日間)
Arash
Arash 2017 年 9 月 6 日
編集済み: Jacob Ward 2017 年 9 月 6 日
Hello All,
I have a folder with different .dat files in it (with different names such as a.dat, b.dat and...). I have created a cell with C={'a.dat', 'b.dat', 'c.dat', ...}. Now I want to read all of those files in a For loop. For example for the i=1 in the loop, I want to read the 'a.dat", for i=2, 'b.dat', and so on. Do you have any idea how can I do that? I am trying to use something similar to fid(i) = fopen(sprintf('C(1,i)'),'rt'); but it does not work.
Thanks

採用された回答

Jacob Ward
Jacob Ward 2017 年 9 月 6 日
編集済み: Jacob Ward 2017 年 9 月 6 日
You don't need to use sprintf. Try the following:
C={'a.dat', 'b.dat', 'c.dat',...};
for i = 1:n
fid(i) = fopen(C{i},'rt')
end
  2 件のコメント
Guillaume
Guillaume 2017 年 9 月 6 日
Huh? That's a very roundabout way to access the content of a cell array
Jacob Ward
Jacob Ward 2017 年 9 月 6 日
Wow, yeah I had a mind blank. Changed my answer to reflect my newfound common sense.

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

その他の回答 (1 件)

Guillaume
Guillaume 2017 年 9 月 6 日
編集済み: Guillaume 2017 年 9 月 6 日
You use curly braces {} to access the content of a cell array. You don't use sprintf, or strjoin or any special function. Therefore:
for i = 1:n
fid = fopen(C{i}, 'rt');
%...
end
I would recommend using the full path to the files instead of relative paths.
folder = 'C:\somewhere\someplace';
filenames = {'a.dat', 'b.dat'};
for fileindex = 1:numel(filenames)
fid = fopen(fullfile(folder, filenames{fileindex}), 'rt');
%...
end
and use meaningful variable names as I've done above instead of C, i, etc.
Also, you could use dir to get the list of files instead of building it yourself.
Oh, and finally don't use 2d indexing (C{1, i}) on vectors when linear indexing (C{i}) is simpler and works regardless of the shape of the vector (column, row, along 3rd dimension, etc.)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by