How to load different data files in a for loop

3 ビュー (過去 30 日間)
Yvonne Visser
Yvonne Visser 2015 年 2 月 16 日
コメント済み: Yvonne Visser 2015 年 2 月 19 日
I am trying to do an analysis on 6 different sets of data with the names log_1 - log_6. I put the analysis in a for loop but can't get MATLAB to load the next file for each iteration. Basically, this is what I want to do:
for n=1:6
load log_n.mat
*rest of analysis*
*calculation* = newvariable(n)
end
to create an array called newvariable with the outcome for each set of data in it. But MATLAB gives the following error:
Error using ==> load
Unable to read file log_n.mat: No such file or directory.
which makes sense because log_n doesn't exist.
How do I load the different files in the for loop so the analysis will be done on the right data?
  1 件のコメント
Stephen23
Stephen23 2015 年 2 月 16 日
編集済み: Stephen23 2015 年 2 月 16 日
Learn about sprintf , it makes this easy!

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

採用された回答

Jos (10584)
Jos (10584) 2015 年 2 月 16 日
for n=1:6,
filename = sprintf('log_%d.mat',n)
S = load(filename)
% S is a structure with the variables inside the mat file as its fields.
% If you expect a variable called V, you can check this using ISFIELD
if isfield(S,V)
% ...
else
disp(['The file "' filename '" did not contain the variable "' V '"']) ;
end
end
  1 件のコメント
Yvonne Visser
Yvonne Visser 2015 年 2 月 19 日
Thanks! This worked well :)

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by