MATLAB: Multiplying structures together based on field names

structures

Is there any method to multiply structures together according to their field names? For example,
struct1.a=1;
struct1.b=2;
struct2.a=3;
struct2.b=4;
And the result would be:
struct3.a=3
struct3.b=8

Best Answer

A function to multiply two structures field by field. This needs to be copied into a file on your MATLAB path called multiplyStructs.m
function s3 = multiplyStructs(s1, s2)
%MULTIPLYSTRUCTS multiplies structures field by field
% S3 = MULTIPLYSTRUCTS(S1, S2) returns a structure S3 with those fields
% that are common to S1 and S2. The value of each such field is the
% matrix product of the values of the corresponding fields of S1 and S2.
% get common field names
f1 = fieldnames(s1);
fnames = f1(ismember(f1, fieldnames(s2)));
% multiply
for k = 1:length(fnames)
fname = fnames{k};
s3.(fname) = s1.(fname) * s2.(fname); % matrix product
end
end
Test code:
struct1.a = 1;
struct1.b = 2;
struct1.c = 3; % will be ignored as no match
struct1.d = 4;
struct2.a = 3;
struct2.b = 4;
struct2.d = 10;
struct3 = multiplyStructs(struct1, struct2)
An alternative way, which works only if all the structures have the same fields, but which generalises more readily to multiple structures, is to use this function:
function s = structProd(svec)
%STRUCTPROD returns the field-by-field products of a structure array
% S = STRUCTPROD(SARR) takes a structure array and returns a scalar
% structure with the same fields. The value of each field of S is the
% product of the values of the corresponding fields of SARR, which must
% all be numerical scalars.
%
% See also: prod
fnames = fieldnames(svec);
for k = 1:length(fnames)
fname = fnames{k};
s.(fname) = prod([svec.(fname)]);
end
end
and then put the structures into an array (which indeed might be the best way to store them to start with. Here's the test code:
struct1.a = 1;
struct1.b = 2;
struct1.d = 4;
struct2.a = 3;
struct2.b = 4;
struct2.d = 10;
struct3.a = -1;
struct3.b = -1;
struct3.d = -1;
struct4.a = 4;
struct4.b = 1;
struct4.d = 2;
struct5 = structProd([struct1 struct2 struct3 struct4])