matlab - 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]
我也完全愿意以不同的方式建立索引。
解决方案
使用上面的评论,这是最终的解决方案:
% 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)
推荐阅读
- flutter - Flutter 中的状态是什么?
- ngxs - 需要使用 @ngxs/storage-plugin 存储的数据的命名空间
- sql - @var IS Null 条件导致聚集索引扫描
- regex - 仅当 n 行之前的另一个字符串在任何支持 PCRE 的文本编辑器中匹配时,正则表达式匹配 n 行之后的字符串
- java - Tapestry (5.7.2) - 通过 XHR 从内部组件刷新外部区域
- javascript - 使用for循环查找对象中属性值的函数,但它始终返回No such value
- windows - vscode liveshare中是否可以共享端口443(https)?
- multithreading - 如何在 Clojure 中处理并发用户请求?
- css - Angular - 使用 Mat Paginator,如何删除页面按钮上的背景颜色?
- docker - 如何更改在 docker 下运行的 Logstash 的默认 URL?