To combine data, I want to load one data as the base assign the data to another variable (e.g. naming it as base_data). Then load in another data and loop through all of its fields. If the current field doesn't exist in the base data, add the field to the base data. (e.g. base_data.fieldname = data.fieldname). Then I want to save the base_data to file. Can I know the commands to do this in Matlab?
Asked
Active
Viewed 1,168 times
1 Answers
1
Use dynamic field names:
base_data = load('A.mat');
B = load('B.mat');
fn = fieldnames(B);
for ii=1:length(fn)
fieldname = char(fn(ii));
if ~isfield(base_data,fieldname)
base_data.(fieldname) = B.(fieldname);
end
end
save('base_data','base_data')

tmpearce
- 12,523
- 4
- 42
- 60
-
Hi, when I use the above commands, I am able to create a base_data.mat. However, when I use the following commands:- load base_data.mat; base_data.variable1; I get the error:-Reference to non-existent field 'variable1'. Am I making an error? Variable 1 is a field in B.mat. – Sujay Prasad Srivastava Nov 24 '12 at 17:32
-
After you load `base_data`, either use the gui (variable inspector pane) or `disp(fieldnames(base_data))` to show you what is contained in the structure. You can debug from there. You can also set breakpoints in the above code to see if the fields of `B` are getting copied into `base_data` appropriately. It may be that loading your matfiles with the `B=load('B.mat')` syntax isn't giving you what you expect, in which case you may need to rearrange that structure first. – tmpearce Nov 25 '12 at 04:41