Arrays 创建与其他两个字段相减的新字段
我有一个matlab数据结构,它是一个1 x 500的度量值,存储为字段。每个受试者在每个字段中都报告了值。我需要创建一个新的字段,它是已经存在的两个字段的减法。我知道它需要以某种方式包含for循环,但我对如何实现这一点有点迷茫。以下是一个示例:Arrays 创建与其他两个字段相减的新字段,arrays,matlab,struct,field,Arrays,Matlab,Struct,Field,我有一个matlab数据结构,它是一个1 x 500的度量值,存储为字段。每个受试者在每个字段中都报告了值。我需要创建一个新的字段,它是已经存在的两个字段的减法。我知道它需要以某种方式包含for循环,但我对如何实现这一点有点迷茫。以下是一个示例: % 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; % comput
% 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{:});
以下是生成的结构数组:
>> 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
或者,您也可以编写一个简单的for循环:
for i=1:numel(s)
s(i).w = s(i).y - s(i).x;
end
是的,您可以通过动态创建字段来实现。