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

appendmerge

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

Best Answer

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');