Stuct matching utility

Version 1.2.0.0 (1.37 KB) by Ehren
Matches the fields and field order of two structs so that they can be concatenated.
142 Downloads
Updated 6 Nov 2012

View License

function [S1,S2] = matchStructs(S1,S2)
% function [S1,S2] = matchStructs(S1,S2)
%
% Structs must have the same fields with the same order to be concatenated,
% this function will satisfy these requirements.
% Missing fields will be created with empty arrays;
%
% NOTE: fields will be sorted in alphebetical order

% created: eln 120928

% determine needed fields
S1_flds = fields(S1);
S2_flds = fields(S2);
S1_needed = setdiff(S2_flds,S1_flds);
S2_needed = setdiff(S1_flds,S2_flds);


% add missing fields
for i = 1:length(S1_needed), [S1.(S1_needed{i})] = deal(cast([],class(S2(1).(S1_needed{i})))); end
for i = 1:length(S2_needed), [S2.(S2_needed{i})] = deal(cast([],class(S1(1).(S2_needed{i})))); end

% match field orders
S1 = orderfields(S1);
S2 = orderfields(S2);
end

Cite As

Ehren (2024). Stuct matching utility (https://www.mathworks.com/matlabcentral/fileexchange/38407-stuct-matching-utility), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2010b
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on Structures in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.2.0.0

Updated to support logicals

1.1.0.0

This function uses a more robust way of casting the filler fields to cover conditions missed by the previous method.

1.0.0.0