如果 的每个元素x
仅包含fruit
字段的字符串,则可以通过以下方式轻松执行此操作。
toremove = ismember({x.fruit}, 'apple')
x(toremove) = [];
或更简单地说
x = x(~ismember({x.fruit}, 'apple'));
该{x.fruit}
语法将fruit
for each的所有值组合struct
到一个元胞数组中。然后,您可以ismember
在字符串元胞数组上使用将每个字符串与'apple'
. 这将产生一个逻辑数组,其大小x
可用于索引x
.
您也可以使用类似的东西strcmp
而不是ismember
上面的东西。
x = x(~strcmp({x.fruit}, 'apple'));
更新
如果每个都x(k).fruit
包含一个元胞数组,那么您可以使用类似于上述方法的方法并结合cellfun
.
x(1).fruit = {'apple', 'orange'};
x(2).fruit = {'banana'};
x(3).fruit = {'grape', 'orange'};
x = x(~cellfun(@(fruits)ismember('apple', fruits), {x.fruit}));
%// 1 x 2 struct array with fields:
%// fruit
如果您想一次检查多种类型的水果要移除,您可以执行类似的操作。
%// Remove if EITHER 'apple' or 'banana'
tocheck = {'apple', 'banana'};
x = x(~cellfun(@(fruits)any(ismember({'apple', 'banana'}, fruits)), {x.fruit}));
%// Remove if BOTH 'apple' and 'banana' in one
x = x(~cellfun(@(fruits)all(ismember({'apple', 'banana'}, fruits)), {x.fruit}));