7

My question is: What is the difference between S and S(:) if S is an empty struct.

I believe that there is a difference because of this question: Adding a field to an empty struct

Minimal illustrative example:

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

The error given:

A dot name structure assignment is illegal when the structure is empty. Use a subscript on the structure.

4

3 回答 3

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

现在有趣的是,我发现了一种使 MATLAB 崩溃的方法(在 R2013a 上测试):

%# careful MATLAB will crash and your session will be lost!
S = struct();
S = setfield(S, {}, 'g', {}, 0)
于 2013-05-02T17:03:58.550 回答
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

虽然这给出了一个 0x0 结构。

于 2013-05-02T17:43:22.030 回答
0

实际上,两者之间的区别S通常S(:)适用于结构,而不仅仅是空结构。

出现这种情况的一个原因是,这允许您选择是否要访问结构或其内容。

一个实际的例子是[]为了删除某些东西的赋值:

S = struct();
T = struct();

S(:) = []; % An empty struct with all fields that S used to have
T = []; % Simply an empty matrix

S现在是一个空结构,但仍将包含它之前拥有的所有字段。

T另一方面,现在已经简单地变成了空矩阵[]

这两个动作都符合您的预期,如果没有结构及其所有元素之间的区别,这将是不可能的。

于 2013-09-23T12:06:15.450 回答