我在 Matlab 中有一个元胞数组,每个元胞代表一个作为结构对象的金融交易(该元胞数组是之前从 json 文件导入的)。
这是一个测试集的示例,它复制了我的数据的特征,这里代表 3 个事务:
transaction_1 = struct( 'created_on' , '2023-01-22' , 'amount' , 9.60 , 'merchant' , struct('name','ebay') );
transaction_2 = struct( 'created_on' , '2022-11-22' , 'amount' , 6.20 , 'merchant' , struct('name','ikea') );
transaction_3 = struct( 'created_on' , '2019-06-19' , 'amount' , 3.65 , 'merchant' , [] );
transactions = { struct_1 ; struct_2 ; struct_3 };
元胞数组中的每个结构都包含三个字段:
第三笔交易在测试集中没有商户信息,因此
transactions{3}.merchant
返回空。
现在我希望将各个结构中的字段值提取到单独的元胞数组中。以下代码对于日期和金额正确工作
created_on = cellfun(@(x) x.created_on , transactions , 'UniformOutput' , false);
amounts = cellfun(@(x) x.amount , transactions , 'UniformOutput' , false);
merchant_names = cellfun(@(x) x.merchant.name , transactions , 'UniformOutput' , false);
但对于商家来说会失败,因为在某些情况下该名称不存在。有没有一种好的方法可以做到这一点,而不需要对所有条目进行循环?
我首先将
merchant
字段提取到元胞数组中,然后对其进行处理。
首先,将结构体元胞数组转换为结构体数组将使一切变得更容易。假设所有结构都是兼容的,如您的示例所示,那么我们可以这样做:
transactions = [transactions{:}];
我们现在有一个 1x3 结构体数组。我们现在可以轻松地将各个字段提取到元胞数组中,如下所示:
merchant = {transactions.merchant}
一些单元格将是空数组,其他单元格将是结构体。让我们看看哪个是哪个:
index = ~cellfun('isempty', merchant)
我们现在创建一个元胞数组来包含商家名称,并用商家所在的名称填充它:
merchant_name = cell(size(index));
merchant_name(:) = {''};
merchant_name(index) = cellfun(@(x) x.name, merchant(index), 'UniformOutput', false);
现在
merchant_name
是元胞数组:
merchant_name =
1x3 cell array
{'ebay'} {'ikea'} {0x0 char}