Search code examples
matlabmatlab-struct

Where are these `New Name` and `[]` coming from?


I'm learning about structure iteration, and trying to output things in the loop

patient(1).name = 'John Doe';
patient(1).billing = 127.00;
patient(1).test = [79, 75, 73; 180, 178, 177.5; 220, 210, 205]; 
patient(2).name = 'Ann Lane';
patient(2).billing = 28.50;
patient(2).test = [68, 70, 68; 118, 118, 119; 172, 170, 169]; 

fields = fieldnames(patient)

%numel is number of elements
for i=1:numel(fields)
  fields(i)
  patient.(fields{i})
end

During this patient.(fields{i}), it gives 'New Name' and [] which are not part of my struct. Where are those values coming from?

The output is:

ans = 'name'
ans = John Doe
ans = Ann Lane
ans = New Name
ans = 'billing'
ans = 127
ans = 28.5000
ans = []
ans = 'test'
ans = 79.0000   75.0000   73.0000
     180.0000  178.0000  177.5000
     220.0000  210.0000  205.0000
ans = 68    70    68
     118   118   119
     172   170   169
ans = []

Solution

  • You must have previously assigned patient(3).name = 'New Name' and since your code only over-writes the first and second elements of patient, the third element remains untouched and is therefore appearing during your looping.

    You can check this by using size or numel

    numel(patient) 
    %   3
    

    To prevent this, you can either initialize your struct to an empty struct prior to assignment

    % Initialize it
    patient = struct()
    
    % Now populate
    patient(1).name = 'whatever';
    

    Or explicitly clear the variable clear patient to ensure that this doesn't happen.

    clear patient
    
    % Now populate it
    patient(1).name = 'whatever';
    

    Also, as a side-note, the reason that the other fields are [] is because if you add a new field to an existing struct array, then all struct entries in the array will receive [] as the value for the new field

    clear patient
    
    patient(2).name = 'New Name';
    patient(1).name = 'Test';
    
    % Add a new field only to patient(2)
    patient(2).date = 'today';
    
    % patient(1).date becomes []
    patient(1).date
    %   []