how can I select .mat file to load from part of the name?

10 ビュー (過去 30 日間)
Pasquale
Pasquale 2019 年 3 月 20 日
コメント済み: Pasquale 2019 年 3 月 21 日
I need to load the following files one by one, using a for loop, because at each iteration I have to do some calculation with the variables of these files:
110-1-D2-6-sum.mat
110-1-D3-7-sum.mat
110-1-E0-8-sum.mat
110-1-E0-12-sum.mat
How can I do this? The problem is that the name changes not only in the last number, but also in the letters. I would load them using part of the name (D2-6; D3-7....)

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 20 日
projectdir = pwd; %or appropriate directory name
looking_for = 'D2-6';
dinfo = dir( fullfile(projectdir, ['*' looking_for '*.mat']) );
filenames = fullfile(projectdir, {dinfo.name});
num_files = length(filenames);
results = cell(num_files, 1);
for K = 1 : num_files
this_file = filenames{K};
results{K} = Process_a_file(this_file);
end
  4 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 21 日
Process_a_file would be a function that you would provide that would accept the file name and do whatever was appropriate with it. That would probably include load()
datastruct = load(filename); %returns a structure of all of the variables contained
var1 = datastruct.var1; %extract a particular one into a more convenient form
Pasquale
Pasquale 2019 年 3 月 21 日
With datastruct, it seems to work. Thanks a lot

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

その他の回答 (1 件)

Pasquale
Pasquale 2019 年 3 月 20 日
Thanks for your answer. In my problem I have about 20 files with that kind of name. All of them must be loaded, but not together; that's why I need a for loop to load them one by one. Should I write all the "labels" inside looking_for in this way?
looking_for = ['D2-6' 'D3-7' 'E0-8'....]
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 3 月 20 日
The code I posted does load one by one. It loops through all of the file names that match the looking_for and processes them one at a time. Your sample display only happens to show one file for each particular combination of letter-number-dash-number and if that holds true then it would only match one file, but I wrote the code with the assumption that several might match.
The code above is not designed to look for multiple substrings; it would have to be modified for that.
Pasquale
Pasquale 2019 年 3 月 21 日
Ok, thanks, I understood; surely this could be helpful for me. My problem is a bit different, and maybe simpler: as you said, I have only one file for each combination. So I would do something llike this:
label=[D2-6' 'D3-7' 'E0-8'...nlabel]
for i=1:length(label)
load(filename(label(i))
end
Is it possible?

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

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT-Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by