Subtract all values from one structure from another structure

25 views (last 30 days)
I have two structures with various different sections of a dataset. Both structures are identically sized - they are set up exactly the same, with each array within the structure the same length as the corresponding array in the other structure. Is there any way to subtract one structure from another, to create a new strucure, so the values in each corresponding array are subtracting from each other. I have not been able to figure out a way of doing this - can it be done? Or will I have to extract these values from the structure first?
e.g.
%% create the structure
data.x=(0:5);
data.y=(0:3:33);
data1.x=(0:2:10);
data1.y=(0:6:66)
Here, I would want the following to be done:
data.x - data1.x = data2.x
data.y - data1.y = data2.y
Is this possible? Or do I need to take a different approach?

Accepted Answer

Rik
Rik on 17 Mar 2023
The only way I can think of is looping through the fields:
%% create the structure
data.x=(0:5);
data.y=(0:3:33);
data1.x=(0:2:10);
data1.y=(0:6:66);
data2 = data;
fields = fieldnames(data);
for n=1:numel(fields)
data2.(fields{n}) = data.(fields{n}) - data1.(fields{n});
end
disp(data2)
x: [0 -1 -2 -3 -4 -5] y: [0 -3 -6 -9 -12 -15 -18 -21 -24 -27 -30 -33]

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!