Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 407
Dennis Jaheruddin Avatar asked May 02 '13 16:05

Dennis Jaheruddin


2 Answers

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)
like image 55
Amro Avatar answered Sep 29 '22 11:09

Amro


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

like image 24
Jonas Avatar answered Sep 29 '22 10:09

Jonas