Question

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.

Was it helpful?

Solution 2

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

OTHER TIPS

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)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top