Extracting a variable from a series of files contained inside a folder

4 ビュー (過去 30 日間)
Lorenzo Merlino
Lorenzo Merlino 2024 年 2 月 13 日
移動済み: Dyuman Joshi 2024 年 2 月 13 日
The problem is simple: I have a folder which contains 10 .mat files, each of them with a series of variables. What I need to do is to create a code which automatically selects one specific variable (always the same) from each file of said folder, then storing it in a separate matrix which I can use later.
Does anybody have a solution to this?
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2024 年 2 月 13 日
移動済み: Dyuman Joshi 2024 年 2 月 13 日
Refer to this documentation page for importing and exporting multiple files - https://in.mathworks.com/help/matlab/import_export/process-a-sequence-of-files.html
Additionally, use load instead of importdata() for reading the .mat files.

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

採用された回答

Voss
Voss 2024 年 2 月 13 日
% the folder which contains 10 .mat files
file_path = '.';
% the name of the variable to load from each .mat file
variable_name = 'X';
% get file info. note that the files are not in any particular order. if
% you want a specific order, you'll have to take care to do that.
files = dir(fullfile(file_path,'*.mat'));
N = numel(files);
% load each X into a struct array S:
file_names = fullfile({files.folder},{files.name});
S = struct(variable_name,cell(1,N));
for ii = 1:N
S(ii) = load(file_names{ii},variable_name);
end
% if you want to combine the X from each mat file into a single array
X = cat(3,S.(variable_name));
% otherwise, you can just access them through S
  2 件のコメント
Lorenzo Merlino
Lorenzo Merlino 2024 年 2 月 13 日
Great, it worked! Thanks so much.
Voss
Voss 2024 年 2 月 13 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

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