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?
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 structa
has two fields andb
has none:However, this works:
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:I also recommend reading the following:
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
now
EmptyStruct
is the empty struct you desire. So to add new ones