convert 1x5 struct to 1x6 struct in matlab

You can concatenate two structs using square brackets and then use fieldnames to get the field names. If one struct has an extra field compared to the other, you can use rmfield to remove it.

Here's an example:

main.m
% create 1x5 struct (with 5 fields)
s1.a = 1;
s1.b = 'hello';
s1.c = [1 2 3];
s1.d = true;
s1.e = magic(3);

% create 1x6 struct (with 6 fields)
s2 = s1; % copy s1 to s2
s2.f = pi; % add extra field

% concatenate s1 and s2 using square brackets
s = [s1 s2];

% get field names
fields = fieldnames(s);

% check number of fields
numFields = numel(fields);

% remove extra field (if it exists)
if numFields > 6
    s = rmfield(s, fields{end});
end
446 chars
25 lines

gistlibby LogSnag