使用cellfun()从元胞数组提取空结构体字段的报错解决方法
Matlab提取元胞数组中结构体商家名称的无报错方法
问题背景
你有一个存储金融交易的元胞数组,每个元胞是包含created_on、amount、merchant(可选location)字段的结构体。其中merchant字段可能是空数组,或是包含name子字段的结构体。直接用cellfun(@(x) x.merchant.name, transactions, 'UniformOutput', false)提取商家名称时,会因空merchant字段触发报错。
解决方案
在cellfun的匿名函数中加入条件判断,先检查merchant是否非空且包含name字段,再返回对应值,否则返回默认值(比如空字符串):
merchant_names = cellfun(@(x) ... ~isempty(x.merchant) && isfield(x.merchant, 'name') ? x.merchant.name : '', ... transactions, 'UniformOutput', false);
代码说明
~isempty(x.merchant):先排除merchant为空数组的情况isfield(x.merchant, 'name'):确保merchant结构体包含name字段(覆盖部分merchant结构体缺失该字段的极端情况)- 三元运算符
?::满足条件时返回商家名称,否则返回空字符串(可根据需求替换为NaN、[]等自定义默认值)
测试验证
将上述代码应用到你的测试数据中,得到的merchant_names结果为:
{'ebay'; 'ikea'; ''; ''}
完全符合预期,不会触发报错。
内容的提问来源于stack exchange,提问作者teeeeee
相关产品推荐
相关产品推荐

