How to add new element to structure array in Matlab?

41,419

Solution 1

If you're lazy to type out the fields again or if there are too many then here is a short cut to get a struct of empty fields

a.f1='hi'
a.f2='bye'

%assuming there is not yet a variable called EmptyStruct
EmptyStruct(2) = a;
EmptyStruct = EmptyStruct(1);

now EmptyStruct is the empty struct you desire. So to add new ones

a(2) = EmptyStruct; %or cat(1, a, EmptyStruct) or [a, EmptyStruct] etc...



a(2)

ans = 

    f1: []
    f2: []

Solution 2

You can only concatenate structures with identical fields.

Let's denote your second struct by b. As you have already checked, the following won't work, because struct a has two fields and b has none:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct;
[a; b]

However, this works:

a = struct('f1', 'hi', 'f2', 'bye');
b = struct('f1', [], 'f2', []);
[a; b]

If you want to "automatically" create an empty structure with the same fields as a (without having to type all of them), you can either use Dan's trick or do this:

a = struct('f1', 'hi', 'f2', 'bye');

C = reshape(fieldnames(a), 1, []); %// Field names
C(2, :) = {[]};                    %// Empty values
b = struct(C{:});

[a; b]

I also recommend reading the following:

  1. Stack Overflow - What are some efficient ways to combine two structures
  2. Stack Overflow - Update struct via another struct
  3. Loren on the Art of MATLAB - Concatenating structs
Share:
41,419
Suzan Cioc
Author by

Suzan Cioc

Not to be offended

Updated on July 23, 2020

Comments

  • Suzan Cioc
    Suzan Cioc almost 4 years

    How to add new element to structure array? I am unable to concatenate with empty structure:

    >> a=struct;
    >> a.f1='hi'
    
    a = 
    
        f1: 'hi'
    
    >> a.f2='bye'
    
    a = 
    
        f1: 'hi'
        f2: 'bye'
    
    >> a=cat(1,a,struct)
    Error using cat
    Number of fields in structure arrays being concatenated do not match. Concatenation of structure arrays requires that these arrays have the same set of
    fields.
    

    So is it possible to add new element with empty fields?

    UPDATE

    I found that I can add new element if I simultaneously add new field:

    >> a=struct()
    
    a = 
    
    struct with no fields.
    
    >> a.f1='hi';
    >> a.f2='bye';
    >> a(end+1).iamexist=true
    
    a = 
    
    1x2 struct array with fields:
    
        f1
        f2
        iamexist
    

    It is incredible that there is no straight way! May be there is some colon equivalent for structures?