フィルターのクリア

Merging .mat files into 1 file, only containing variables in array form

70 ビュー (過去 30 日間)
Bas
Bas 2016 年 12 月 23 日
コメント済み: Stephen23 2023 年 10 月 16 日
Hi there,
I want to merge 5 .mat files into 1 .mat file. When doing this, the end result is a mat file which contains 1 structure array. I want the result to be a mat file that only contains matrix arrays.
The situation is follows:
- Each mat file contains 11 variables (with the same name), and each variable contains 136000x1 samples.
- The end result should be 1 mat file that contains the 11 variables, but with 136000x5 samples.
Aside of the accepted answer, this code works as well:
clear all
close all
clc
%% loading data
% Create example data
y = load('Data_file1.mat');
z = load('Data_file2.mat');
q = load('Data_file3.mat');
vrs = fieldnames(y);
if ~isequal(vrs,fieldnames(y))
error('Different variables in these MAT-files')
end
for k = 1:length(vrs)
x.(vrs{k}) = [y.(vrs{k});z.(vrs{k});q.(vrs{k})];
end
% Save result in a new file
save('Data.mat','-struct','x')

採用された回答

Jan
Jan 2017 年 1 月 16 日
編集済み: Jan 2021 年 2 月 4 日
FileList = dir(fullfile(Folder, '*.mat')); % List of all MAT files
allData = struct();
for iFile = 1:numel(FileList) % Loop over found files
Data = load(fullfile(Folder, FileList(iFile).name));
Fields = fieldnames(Data);
for iField = 1:numel(Fields) % Loop over fields of current file
aField = Fields{iField};
if isfield(allData, aField) % Attach new data:
allData.(aField) = [allData.(aField), Data.(aField)];
% [EDITED]
% The orientation depends on the sizes of the fields. There is no
% general method here, so maybe it is needed to concatenate
% vertically:
% allData.(aField) = [allData.(aField); Data.(aField)];
% Or in general with suiting value for [dim]:
% allData.(aField) = cat(dim, allData.(aField), Data.(aField));
else
allData.(aField) = Data.(aField);
end
end
end
save(fullfile(Folder, 'AllData.mat'), '-struct', 'allData');
  16 件のコメント
Rakesh
Rakesh 2023 年 10 月 16 日
i have 3 different file location and 50 .mat file in each i just want to put then in one file as a matrix. please help
Stephen23
Stephen23 2023 年 10 月 16 日
@Rakesh: what have you tried so far? What do the .MAT file contain?

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

その他の回答 (4 件)

John BG
John BG 2016 年 12 月 23 日
use the save function specifying the variable names:
1.
let's say you have saved your 5 in these 5 .mat files
save var1.mat v1
save var2.mat v2
save var3.mat v3
save var4.mat v4
save var5.mat v5
2.
if not already in the workspace, load them
load var1.mat
load var2.mat
load var3.mat
load var4.mat
load var5.mat
now v1 v2 v3 v4 v5 should be in the workspace
3. combine all the variables you want in a single .mat file
save vars12345.mat v1 v2 v3 v4 v5
Now you have the 5 variables that were in separate .mat files in single .mat file
if you find these lines useful would you please mark my answer as Accepted Answer?
To any other reader, please if you find this answer of any help, click on the thumbs-up vote link,
thanks in advance for time and attention
John BG
  3 件のコメント
TheNightstalk3r
TheNightstalk3r 2016 年 12 月 23 日
編集済み: TheNightstalk3r 2016 年 12 月 23 日
save [ your made-up filename].mat [ the variable you want to save]
is I believe what he is saying. However you need your variables already loaded in your workspace I'd think
John BG
John BG 2017 年 1 月 18 日
correct, if not loaded, load first the variables, thanks Nighttalker

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


John BG
John BG 2016 年 12 月 26 日
編集済み: John BG 2016 年 12 月 26 日
Ok,
If you have exactly the same variable names in different .mat files and attempt loading them, you have to change variables identically named, otherwise the last load will override previous values of variables with same names.
I wrote a short script for another answer asking to merge figures in same file. I can modify that script to help you solve this question.
But if you tell me that the names of the already stored variables cannot be changed then I will generate a list and alter variable names that attempt override.
how do you want me to proceed?
  2 件のコメント
Bas
Bas 2016 年 12 月 26 日
編集済み: Bas 2016 年 12 月 26 日
> If you have exactly the same variable names in different .mat files and attempt loading them, you have to >change variables identically named, otherwise the last load will override previous values of variables with >same names.
I was aware of the problem, but the names of the stored variables cannot be changed. If you could write a new script, that would be nice.
Stephen23
Stephen23 2023 年 10 月 16 日
"If you have exactly the same variable names in different .mat files and attempt loading them, you have to change variables identically named, otherwise the last load will override previous values of variables with same names."
Keeping the names the same in every .MAT file is the way to write simple, efficient, robust code. It is very easy to avoid overwriting the LOADed data in a loop (hint: always LOAD into an output argument and access its fields).
Following the bad advice given in this answer and changing the names in every file is how you will force yourself into writing slow, complex, obfuscated, inefficient, fragile code. Best avoided.

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


John BG
John BG 2016 年 12 月 27 日
the following is really basic but it does what you asked for, there are some points that you may want to improve but improvements take time, they can be built them gradually:
1.
put all .mat files in same folder
cd 'folder_mat_files'
2.
get in the folder where all .mat files to merge have been placed
system('dir /o:n /b > list.txt')
3.
build list
fid=fopen('list.txt')
s1=textscan(fid,'%s')
fclose(fid)
[sz1 sz2]=size(s1{1})
4.
PENDING
remove list.txt from s1
5.
getting var names stored in .mat files
C={};
for k=1:1:sz1
if regexp(s1{1}{k},'.mat')
C{k}=who('-file',s1{1}{k})
end;
end;
[szC1 szC2]=size(C) % szC2 should be sz1-1 amount of .mat files
6.
simple case just 2 .mat files to merge
L=combinations([1:1:numel(C{1})],[1:1:numel(C{1})])
[sz1L sz2L]=size(L)
C2=C;
7.
first in has priority, any variable in second .mat file with same name as in 1st .mat is renamed
for k=1:1:sz1L
if strcmp(C{1}{L(k,1)},C{2}{L(k,2)})
C{2}{L(k,2)}=[C{2}{L(k,2)} '_copy']
end
end
8.
create file to collect input .mat files adding var string named L12 containing all var names
L12=['merge of ' s1{1}{1} ' ' s1{1}{2}]
save('merge_file.mat','L12')
9.
% for k=1:1:szC2 % this for is to process more than 2 .mat files to merge, v1 just 2 .mat files
[sz1C1 sz2C1]=size(C{1})
for n=1:1:sz1C1
load(s1{1}{1},'-mat',C{1}{n})
save('merge_file.mat',C{1}{n},'-append')
clearvars C{1}{n}
end
[sz1C2 sz2C2]=size(C{2})
for n=1:1:sz1C2
load(s1{1}{2},'-mat',C{2}{n})
eval([C{2}{n} '=' C2{2}{n} ])
save('merge_file.mat',C{2}{n},'-append')
clearvars C{2}{n}
end
% end
awaiting answer
John BG
  1 件のコメント
Jan
Jan 2017 年 1 月 16 日
編集済み: Jan 2017 年 1 月 17 日
@John BG: It is very inefficient to call dir through the system command, because it can be called from Matlab directly.
Please do not post functions from the file exchange without the required license file. The BSD license is clear in this point. Better use a link to the original submission. Then future updates or bugfixes are considered also: http://www.mathworks.com/matlabcentral/fileexchange/23080-combinations

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


Roar Andreassen
Roar Andreassen 2021 年 2 月 3 日
編集済み: Jan 2021 年 2 月 4 日
function ans = mergeallmatfiles % Merge all mat files in folder
% The set of var. names must be the same in all *.mat files
% NOTE: No error catching!
Folder=pwd; % Read name of current folder
FileList = dir(fullfile(Folder, '*.mat')); % List of all MAT files
allData = struct();
for iFile = 1:numel(FileList) % Loop over found files
Data = load(fullfile(Folder, FileList(iFile).name));
Fields = fieldnames(Data);
for iField = 1:numel(Fields) % Loop over fields of current file
aField = Fields{iField};
if isfield(allData, aField) % Attach new data:
allData.(aField) = [allData.(aField); Data.(aField)]; % Note: must be semicolon
else
allData.(aField) = Data.(aField);
end
end
end
save(fullfile(Folder, 'AllData.mat'), '-struct', 'allData');
end
% Thanks to Jan: https://se.mathworks.com/matlabcentral/answers/318025-merging-mat-files-into-1-file-only-containing-variables-in-array-form
% Regards. RA
  1 件のコメント
Jan
Jan 2021 年 2 月 4 日
編集済み: Jan 2021 年 2 月 4 日
See [EDITED] in my answer and Walter's comment .
Do not use "ans" as output variable.

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

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by