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

11 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Walter Roberson
Walter Roberson il 1 Ott 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');

Più risposte (1)

Stephen23
Stephen23 il 1 Ott 2019
Modificato: Stephen23 il 1 Ott 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]

Categorie

Scopri di più su File Operations in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by