Following assumes you have two structure arrays with an arbitrary number of matching fields (n
- the same for both structs) which is not nested (no A.field1.field2
)
Vanilla loop:
x = 2;
y = 3;
names = fieldnames(A); % returns n x 1 cell array
for n = 1:length(names)
C.(names{n}) = x*A.(names{n}) + y*B.(names{n});
end
Output:
C =
field1: [14 19 24]
field2: 37
Alternative using cellfun:
x = 2;
y = 3;
names = fieldnames(A);
A2 = struct2cell(A);
B2 = struct2cell(B);
C2 = cellfun(@(A,B) x*A+3*B, A2,B2,'UniformOutput',0);
C2 = cell2struct(C2,names)
Output:
C2 =
field1: [14 19 24]
field2: 37