Stuct matching utility

Version (1.37 KB) by Ehren
Matches the fields and field order of two structs so that they can be concatenated.


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

Cite As

Ehren (2023). Stuct matching utility (, MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2010b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes

Updated to support logicals

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