如何在matlab中添加结构中所有字段的值?
How to add the values of all the fields in a struct in matlab?
我有一个结构可以说 ABC
的维度为“1*100”结构,它有一个名为 EFG
的字段,每个字段的值都为 1.6
。
我需要使用 MATLAB 得到 1.6+1.6+1.6+.......+1.6
100 次。
我尝试使用 sum
,但它不适合这个。如何做到这一点?
Sum(ABC(:).EFG)
sum(ABC(:).EFG,2)
这些都不起作用
你需要括号:
for ii = 1:100 % Just creating the struct
ABC(ii).EFG = 1.6; % 1x100 struct with the field EFG
end
sum([ABC(:).EFG])
ans =
160.0000
注意 [ABC(:).EFG]
.
两边的括号
原因是因为如果没有它,您会从 ABC(:).EFG
获得无法在 sum
中使用的输出:
ABC(:).EFG
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
连接它,你会得到一些你可以使用的东西:
[ABC(:).EFG]
ans =
1.6000 1.6000 1.6000 1.6000 1.6000
我有一个结构可以说 ABC
的维度为“1*100”结构,它有一个名为 EFG
的字段,每个字段的值都为 1.6
。
我需要使用 MATLAB 得到 1.6+1.6+1.6+.......+1.6
100 次。
我尝试使用 sum
,但它不适合这个。如何做到这一点?
Sum(ABC(:).EFG)
sum(ABC(:).EFG,2)
这些都不起作用
你需要括号:
for ii = 1:100 % Just creating the struct
ABC(ii).EFG = 1.6; % 1x100 struct with the field EFG
end
sum([ABC(:).EFG])
ans =
160.0000
注意 [ABC(:).EFG]
.
原因是因为如果没有它,您会从 ABC(:).EFG
获得无法在 sum
中使用的输出:
ABC(:).EFG
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
ans =
1.6000
连接它,你会得到一些你可以使用的东西:
[ABC(:).EFG]
ans =
1.6000 1.6000 1.6000 1.6000 1.6000