I have a matlab data structure that is 1 x 500 for a whole plethora of measures, stored as fields. Each subject has values reported in each field. I need to create a new field that is the subtraction of two fields that already exist. I know that it needs to involve a for loop somehow, but I'm a bit lost how to accomplish this.
Asked
Active
Viewed 54 times
1 Answers
1
Here is an example:
% lets create a 1x2 structure array with two fields x and y
clear s
s(1).x = 1;
s(1).y = 10;
s(2).x = 5;
s(2).y = 8;
% compute the subtraction of the values y-x
z = num2cell([s.y] - [s.x]);
% create the new field
[s.z] = deal(z{:});
Here is the resulting structure array:
>> whos s
Name Size Bytes Class Attributes
s 1x2 912 struct
>> s(1)
ans =
x: 1
y: 10
z: 9
>> s(2)
ans =
x: 5
y: 8
z: 3
Alternatively, you could always write a straightforward for-loop:
for i=1:numel(s)
s(i).w = s(i).y - s(i).x;
end

Amro
- 123,847
- 25
- 243
- 454