删除空结构字段Matlab

时间:2012-08-08 14:00:38

标签: matlab structure field

我遇到了以下问题:我有一系列结构,如:

A.B(1,1).x = 'string'
A.B(1,1).y = 12
A.B(1,2).x = []
A.B(1,2).y = []
A.B(1,3).x = 'string2'
A.B(1,3).y = 4

我想从这个结构中删除空的2.行,最后得到(1,1)和(1,3)的字段。 我试图转换为单元格,删除然后返回结构,但这样我必须重新键入字段的名称。 怎么可能这样做?可以在没有结构转换的情况下完成吗?

TIA!

1 个答案:

答案 0 :(得分:1)

使用循环或arrayfun确定哪些数组元素为空:

empty_elems = arrayfun(@(s) isempty(s.x) & isempty(s.y),A.B)

返回:[0 1 0]

empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), A.B);

检查所有字段是否为空(使用any而不是all检查是否有任何元素为空而不是全部。

然后使用logical indexing删除它们:

A.B(empty_elems) = [];

在评论中完整解决您的问题:

% find array elements that have all fields empty:
empty_elems = arrayfun(@(s) all(structfun(@isempty,s)), A.B);

% copy non-empty elements to a new array `C`:
C = A.B(~empty_elems);

% find elements of C that have y field >3
gt3_elems = arrayfun(@(s) s.y<3,C);

% delete those form C:
C(gt3_elems) = [];

逐步执行此代码并分析中间变量以了解发生了什么。应该很清楚。

相关问题