首页 > 解决方案 > Matlab - 将非标量嵌套结构与空字段连接而不会丢失正确的索引

问题描述

在 Matlab 中,有没有办法在不丢失空字段的情况下连接非标量结构?这干扰了我在结构中索引的能力。

出于内存管理的原因,我不希望用 NaN 填充我的所有“y”字段,但如果这是唯一的解决方法,我可以这样做。

“代码”总是完全填充并且没有空单元格。“y”可以完全填充,但通常不是。

我提供了一个简单的例子:简化的结构(实际上是数以万计的条目,有 50 多个字段)

% create example structure
x = struct('y',{1 [] 3 4},'code', {{'a'}, {'b'}, {'c'}, {'b'}});
% concatenate
out = [x.y];
% find indices with code 'b'
ind = find(strcmpi([x.code], 'b'));
% desired output
outSub = out(ind)

希望产出:

out = [1 NaN 3 4]

相反,我得到:

out = [1 3 4]

当尝试使用代码创建索引以查找与所需代码值匹配的值,这显然不起作用。
错误:索引超出数组元素的数量 (3)。

所需的输出将产生:

out = [2 4];
outSub = [NaN 4]

我也完全愿意以不同的方式建立索引。

标签: matlab

解决方案


使用上面的评论,这是最终的解决方案:

% create example structure
x = struct('y',{1 [] 3 4},'code', {{'a'}, {'b'}, {'c'}, {'b'}});
% concatenate
out = {x.y};
% find indices with code 'b'
ind = find(strcmpi([x.code], 'b'));
% desired output - cell array
outSubCell = out(ind);
% substitute [] for NaN
outSubCell(cellfun('isempty',outSubCell)) = {NaN};
% convert output to double array
outSub = cell2mat(outSubCell)

推荐阅读