访问非标量结构的所有记录的某个字段中的第 i 个元素
Access i-th element in a certain field of all records of a non-scalar structure
我有一个名为 mystruct 的结构,其中包含两个字段:field1
、field2
。典型例子:
mystruct(1).field1 = 'a'
mystruct(1).field2 = [100 200 300] % an array of elements
mystruct(2).field1 = 'b'
mystruct(2).field2 = [700 800 900] % an array of elements
如何在不循环的情况下访问每条记录中 field2
的第一个元素(例如上例中的 100 和 700)?
一个优雅的解决方案可以使用 arrayfun
:
ii = 1;
out = arrayfun(@(x) x.field2(ii), mystruct)
这基本上是这个简单循环的另一种表示法:
ii = 1;
for jj = 1:numel(mystruct)
out(jj) = mystruct(jj).field2(ii);
end
如果您有很多个字段并且所有数组的长度都相同,那么您可以考虑以下解决方案,更矢量化,也许更快一点。
ii = 1;
X = vertcat( mystruct(:).field2 )
out = X(:,ii)
out =
100
700
我有一个名为 mystruct 的结构,其中包含两个字段:field1
、field2
。典型例子:
mystruct(1).field1 = 'a'
mystruct(1).field2 = [100 200 300] % an array of elements
mystruct(2).field1 = 'b'
mystruct(2).field2 = [700 800 900] % an array of elements
如何在不循环的情况下访问每条记录中 field2
的第一个元素(例如上例中的 100 和 700)?
一个优雅的解决方案可以使用 arrayfun
:
ii = 1;
out = arrayfun(@(x) x.field2(ii), mystruct)
这基本上是这个简单循环的另一种表示法:
ii = 1;
for jj = 1:numel(mystruct)
out(jj) = mystruct(jj).field2(ii);
end
如果您有很多个字段并且所有数组的长度都相同,那么您可以考虑以下解决方案,更矢量化,也许更快一点。
ii = 1;
X = vertcat( mystruct(:).field2 )
out = X(:,ii)
out =
100
700