How can I load my data from a variable filename

Hello, How can I load 80 files(.mat) from folder each has a number ex: file_1, file_2, file_3 ...file_80. What I did the following:
for x= 1:80
load ('file_x.mat')
But it's not working: gave me the following error: Error using load Unable to read file 'file_x.mat': no such file or directory.

 採用された回答

Sebastian Castro
Sebastian Castro 2015 年 7 月 29 日

5 投票

You need to do this by converting the numerical value of "x" to a string and concatenating that with the rest of the file name string. For example:
for x= 1:80
load (['file_' num2str(x) '.mat'])
end
- Sebastian

5 件のコメント

Stephen23
Stephen23 2015 年 7 月 29 日
編集済み: Stephen23 2015 年 7 月 29 日
Note that it is much better to assign the data into an output variable, like this:
for k = 80:-1:1
S(k) = load(sprintf('file_%d.mat',k));
end
This avoids the need to dynamically name and access those variables.
Sebastian Castro
Sebastian Castro 2015 年 7 月 29 日
Good call. Thanks for the answer upgrade!
Marta Caneda Portela
Marta Caneda Portela 2020 年 6 月 19 日
I have a question because I have the same problem but the files are named file_000000 until file_000788. How would I do that? Thank you!
Steven Lord
Steven Lord 2020 年 6 月 19 日
Are those the only files with that pattern of name in your directory?
D = dir('file_000*');
for k = 1:numel(D)
fprintf('Processing file %s.\n', D(k).name)
end
Shahzanani Senin
Shahzanani Senin 2020 年 9 月 5 日
I have the question also because I have the same problem to load the data. I have 248 files with different name which is 94 files of ADmaskMean_AD_1 until ADmaskMean_AD_94, and 154 files of ADmaskMean_NORMAL_1 until ADmaskMean_NORMAL_154. How can I do that? Thank you!

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by