如何从 MATLAB 结构数组中删除空字符串
How to remove empty strings from a MATLAB array of structs
我有一个 MATLAB 结构数组,其中包含一个名为 image_name
的字段。有一些条目
x(n).image_name = []
(即结构数组的第 n 行有一个 image_name
为空)
我想按照
的方式尝试删除它们
idx = [x.image_name] == []
x(idx) = [];
但无法获取空字符串的索引。我尝试的每个变体都会产生错误。
如何找到空字符串的行索引,以便删除它们?
您可以使用 {}
将名称转换为元胞数组,然后使用 isempty
(在 cellfun
内)查找空条目并将其删除。
ismt = cellfun(@isempty, {x.image_name});
x = x(~ismt);
或在一行中
x = x(~cellfun(@isempty, {x.image_name}));
更新
正如 在评论中提到的,使用 'isempty'
而不是构造匿名函数要快得多。
x = x(~cellfun('isempty', {x.image_name}));
我有一个 MATLAB 结构数组,其中包含一个名为 image_name
的字段。有一些条目
x(n).image_name = []
(即结构数组的第 n 行有一个 image_name
为空)
我想按照
的方式尝试删除它们idx = [x.image_name] == []
x(idx) = [];
但无法获取空字符串的索引。我尝试的每个变体都会产生错误。
如何找到空字符串的行索引,以便删除它们?
您可以使用 {}
将名称转换为元胞数组,然后使用 isempty
(在 cellfun
内)查找空条目并将其删除。
ismt = cellfun(@isempty, {x.image_name});
x = x(~ismt);
或在一行中
x = x(~cellfun(@isempty, {x.image_name}));
更新
正如 'isempty'
而不是构造匿名函数要快得多。
x = x(~cellfun('isempty', {x.image_name}));