空Matlab结构S与所有元素S(:)之间的区别

Den*_*din 7 matlab matlab-struct

我的问题是:if S和empty 之间有什么区别.S(:)S

我认为由于这个问题存在差异: 将字段添加到空结构中

最小的说明性示例:

S = struct(); %Create a struct
S(1) = []; %Make it empty
[S(:).a] = deal(0); %Works
[S.b] = deal(0); %Gives an error
Run Code Online (Sandbox Code Playgroud)

给出的错误:

当结构为空时,点名结构分配是非法的.在结构上使用下标.

Amr*_*mro 7

事实上,这是另一个奇怪的:

>> S = struct('a',{}, 'b',{})
S = 
0x0 struct array with fields:
    a
    b

>> [S(:).c] = deal()
S = 
0x0 struct array with fields:
    a
    b
    c

>> S().d = {}          %# this could be anything really, [], 0, {}, ..
S = 
0x0 struct array with fields:
    a
    b
    c
    d

>> S = subsasgn(S, substruct('()',{}, '.','e'), {})
S = 
0x0 struct array with fields:
    a
    b
    c
    d
    e

>> S = setfield(S, {}, 'f', {1}, 0)
S = 
0x0 struct array with fields:
    a
    b
    c
    d
    e
    f
Run Code Online (Sandbox Code Playgroud)

现在,对于有趣的部分,我发现了一种崩溃MATLAB的方法(在R2013a上测试):

%# careful MATLAB will crash and your session will be lost!
S = struct();
S = setfield(S, {}, 'g', {}, 0)
Run Code Online (Sandbox Code Playgroud)

  • 好一个!另外,我确认了R2012b和R2012a上的seg-fault (3认同)

Jon*_*nas 4

[S(:).b] = deal(0)相当于[S(1:end).b] = deal(0),在您的特定情况下扩展为[S(1:numel(S)).b] = deal(0), 或者[S(1:0).b] = deal(0)。因此,您不会处理该结构的任何元素,而我希望它能够工作,尽管我仍然发现这会添加一个 field 有点令人惊讶b。也许正是这种特殊的奇怪之处,您只能通过显式指定字段列表来访问它,从而被错误捕获。

请注意,如果您想使用 field 创建一个空结构b,您也可以编写

S(1:0) = struct('b',pi) %# pie or no pie won't change anything
Run Code Online (Sandbox Code Playgroud)

尽管这给出了 0x0 结构。