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]

当试图使用code创建索引以查找out中与所需代码值匹配的值时,这显然不起作用
错误:索引超过了数组元素的数量(3(

期望的输出将产生:

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

我对以不同的方式进行索引也持完全开放的态度。

使用上面的注释,这里是最终的解决方案:

% 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)

最新更新