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)
f1 = fieldnames(s1);
fnames = f1(ismember(f1, fieldnames(s2)));
for k = 1:length(fnames)
fname = fnames{k};
s3.(fname) = s1.(fname) * s2.(fname);
end
end
Test code:
struct1.a = 1;
struct1.b = 2;
struct1.c = 3;
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)
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])
Best Answer