Difference between empty Matlab struct S and all elements S(:)

∥☆過路亽.° 提交于 2019-12-18 04:13:02

问题


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.


回答1:


[S(:).b] = deal(0) is equivalent to [S(1:end).b] = deal(0), which expands to [S(1:numel(S)).b] = deal(0), or, in your particular case [S(1:0).b] = deal(0). Thus, you deal to none of the elements of the structure, which I'd expect to work, though I still find it somewhat surprising that this will add a field b. Maybe it is this particular weirdness, which you can only access through explicitly specifying the list of fields, that is caught by the error.

Note that if you want to create an empty structure with field b, you can alternatively write

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

though this gives a 0x0 structure.




回答2:


In fact, here is another weird one for you:

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

Now for the fun part, I discovered a way to crash MATLAB (tested on R2013a):

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



回答3:


Actually the difference between S and S(:) applies to structs in general, not only to empty structs.

One reason why this might be the case, is because this allows you to choose whether you want to access the struct or its contents.

A practical example would be the assignment of [] in order to remove something:

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

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

S is now an empty struct, but would still contain all fields that it had before.

T on the other hand, has now simply become the empty matrix [].

Both actions do what you would expect, and this would not be possible without the distinction between a struct and all its elements.



来源:https://stackoverflow.com/questions/16342688/difference-between-empty-matlab-struct-s-and-all-elements-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!