Subtract all values from one structure from another structure

24 次查看(过去 30 天)
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?

采纳的回答

Rik
Rik 2023-3-17
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]

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by