File Exchange

image thumbnail


version (2.92 KB) by Denis Anikiev
Apply a binary operation function to each field of two input structures

1 Download

Updated 15 Jul 2014

View License

Apply a binary operation function to each field of two input structures, including substructure fields of any level.
C = STRUCTFUN2(FUN, A, B) applies the function specified by FUN to each field of structures A and B, and returns the results in array C.

s1 = struct; s1.a = 1; s1.b = 2; s1.c = struct; s1.c.a = 3;
s2 = struct; s2.a = 0; s2.b = 2; s2.c = struct; s2.c.a = -3;
s3 = structfun2(@plus, s1, s2);

Cite As

Denis Anikiev (2021). structfun2 (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Thomas Gerrits

Good idea! I extended it to support multiple inputs (ND), as well as non-struct inputs.

function out = structfunND(fun, varargin)

var = varargin;

idx_double = cellfun(@(x) isa(x, 'double'), var);
idx_struct = cellfun(@(x) isa(x, 'struct'), var);

out = struct;

% get field names, only common fieldnames are selected
fNames = intersect2(cellfun(@fieldnames, {(var{idx_struct})}, 'un', 0) );
catch % catch error if only one input is a struct
fNames = fieldnames(var{idx_struct});

% Loop each fieldname
for i = 1:length(fNames)

% Loop each input variable
for j = 1:length(var)
if idx_double(j)
varx{j} = var{j};
elseif idx_struct(j)
varx{j} = var{j}.(fNames{i});
error('Error: Unsupported input format!')

% Check for nested structures
if any(cellfun(@isstruct, varx))
out.(fNames{i}) = structfunND(fun, varx{:});
out.(fNames{i}) = fun(varx{:});


MATLAB Release Compatibility
Created with R2014a
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!