将字段添加到空结构 [英] Adding a field to an empty struct
问题描述
假设我有一个大小为0x1的结构S
,其中有字段a
和b
,向其中添加字段c
的最优雅方法是什么?
Assuming I have a struct S
of size 0x1 with the fields a
and b
, what is the most elegant way to add a field c
to it?
通常我可以这样:
S = struct('a',0,'b',0); %1x1 struct with fields a,b
S.c = 0
但是,如果我收到一个空结构,它将不再起作用:
However, if I receive an empty struct this does not work anymore:
S = struct('a',0,'b',0);
S(1) = []; % 0x1 struct with fields a,b
S.c = 0;
% A dot name structure assignment is illegal when the structure is empty.
% Use a subscript on the structure.
我已经想到了两种方法来解决此问题,但是这两种方法都很丑陋,感觉像是变通方法,而不是解决方案. (请注意,也应正确处理非空结构的可能性.)
I have thought of two ways to deal with this, but both are quite ugly and feel like workarounds rather than solutions. (Note the possibility of a non-empty struct should also be dealt with properly).
- 向结构中添加一些内容以确保其不为空,添加字段,然后再次使结构为空
- 使用所需的字段名初始化新结构,将原始结构中的数据填充其中,并覆盖原始结构
我意识到我关心空结构可能很奇怪,但是不幸的是,如果不存在该字段名,那么部分由我管理的代码将崩溃.我查看了help struct
,help subsasgn
,还搜索了给定的错误消息,但到目前为止,我还没有发现任何提示.因此,非常感谢您的帮助!
I realize that it may be odd that I care about empty structs, but unfortunately part of the code that is not managed by me will crash if the fieldname does not exist. I have looked at help struct
, help subsasgn
and also searched for the given error message but so far I have not yet found any hints. Help is therefore much appreciated!
推荐答案
You can use deal
to solve this problem:
S = struct('a',0,'b',0);
S(1) = [];
[S(:).c] = deal(0);
这导致
S =
1x0 struct array with fields:
a
b
c
这也适用于非空结构:
S = struct('a',0,'b',0);
[S(:).c] = deal(0);
结果
S =
a: 0
b: 0
c: 0
这篇关于将字段添加到空结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!