5

我面临以下问题:我有一系列结构,例如:

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) 的字段。我试图转换为单元格,删除然后返回结构,但这样我不得不重新输入字段名称。怎么可能呢?可以在不转换结构的情况下完成吗?

蒂亚!

4

1 回答 1

2

使用循环或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);

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

然后使用逻辑索引删除它们:

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) = [];

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

于 2012-08-08T14:04:16.640 回答