如何从MATLAB结构数组中删除空字符串

use*_*262 0 arrays string matlab struct matlab-struct

我有一个带有字段的MATLAB结构数组image_name.有几个条目在哪里

x(n).image_name = []
Run Code Online (Sandbox Code Playgroud)

(即,struct数组的第n行有一个image_name空的)

我想通过尝试一些方法来删除它们

idx = [x.image_name] == []
x(idx) = [];
Run Code Online (Sandbox Code Playgroud)

但无法获取空字符串的索引.我尝试的每个变体都会产生错误.

如何找到空字符串的行索引,以便删除它们?

Sue*_*ver 5

您可以使用{}将名称转换为单元格数组,然后使用isempty(内部cellfun)查找空条目并将其删除.

ismt = cellfun(@isempty,  {x.image_name});
x = x(~ismt);
Run Code Online (Sandbox Code Playgroud)

或者在一行中

x = x(~cellfun(@isempty, {x.image_name}));
Run Code Online (Sandbox Code Playgroud)

更新

正如@Rody在评论中所提到的,使用'isempty'而不是构建匿名函数要快得多.

x = x(~cellfun('isempty', {x.image_name}));
Run Code Online (Sandbox Code Playgroud)

  • +1.只是为了完整性:使用`cellfun`的字符串参数比使用匿名函数要快得多(即``cellfun('isempty',{x.image_name})`).不确定在最近的MATLAB中是否仍然如此... (4认同)