Filter löschen
Filter löschen

How add multiple variables from one mat files into common mat file in loop ?

14 Ansichten (letzte 30 Tage)
add all the variables from the 1st mat file to common mat file and then load the common mat file and then add all the variables from the second mat file to common mat file in the loop .
eg 1st mat file 6341 x1 variables
2nd mat file 354 x1 variables
common mat file should have 6695 x1

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 1 Okt. 2019
common_file = 'CommonMatFile.mat';
add_first_file = 'FirstFile.mat';
add_second_file = 'SecondFile.mat';
common_vars = load(common_file);
loaded_vars1 = load(add_first_file);
fn1 = fieldnames(loaded_vars1);
for K = 1 : length(fn1)
thisvar = fn1{K};
common_vars.(thisvar) = loaded_vars1.(thisvar);
end
save(common_file, '-struct', 'common_vars');
common_vars = load(common_file);
loaded_vars2 = load(add_second_file);
fn2 = fieldnames(loaded_vars2);
for K = 1 : length(fn2)
thisvar = fn2{K};
common_vars.(thisvar) = loaded_vars2.(thisvar);
end
save(common_file, '-struct', 'common_vars');

Weitere Antworten (1)

Stephen23
Stephen23 am 1 Okt. 2019
Bearbeitet: Stephen23 am 1 Okt. 2019
The solution is really very simple, you do not need to waste time with loops or dynamic fieldnames.
First lets create two example files A.mat and B.mat:
>> A = 'aaa';
>> B = 1:3;
>> save A.mat A
>> save B.mat B
We can now efficiently and simply merge the contents of the two .mat files together:
>> copyfile('A.mat','C.mat') % C will be the merged file
>> S = load('B.mat');
>> save('C.mat','-struct','S','-append')
And that is all you need to do.
Now C.mat contains all of the fields of A.mat and B.mat. Lets have a look:
>> new = load('C.mat')
new =
A: 'aaa'
B: [1 2 3]

Community Treasure Hunt

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

Start Hunting!

Translated by