How to add a new element to a structure array in Matlab?

How to add a new element to the structure array? I cannot connect to an 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 a new element with empty fields?

UPDATE

I found that I can add a new element if I add a new field at the same time:

 >> 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 direct way! Maybe there are a few colon equivalents for structures?

+4
source share
2 answers

You can concatenate structures with the same fields.

Denote your second structure with b . As you already noted, the following will not work because struct a has two fields and b does not:

 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 entering all of them), you can use Dan trick or do the following:

 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:

+3
source

If you are too lazy to enter fields again, or if there are too many, here is a short reduction to get the structure 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 structure you want. So, to add new

 a(2) = EmptyStruct; %or cat(1, a, EmptyStruct) or [a, EmptyStruct] etc... a(2) ans = f1: [] f2: [] 
+3
source

Source: https://habr.com/ru/post/1492901/


All Articles