Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new element to structure array in Matlab?

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?

like image 798
Suzan Cioc Avatar asked Jul 23 '13 08:07

Suzan Cioc


People also ask

How do you add elements to an array in MATLAB?

S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.

How do you assign a value to a struct in MATLAB?

Description. S = setfield( S , field , value ) assigns a value to the specified field of the structure S . For example, S = setfield(S,'a',1) makes the assignment S.a = 1 .

How do you create an array of structures in MATLAB?

To create an array of structures using the struct function, specify the field value arguments as cell arrays. Each cell array element is the value of the field in the corresponding structure array element. For code generation, corresponding fields in the structures must have the same type.


1 Answers

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: []
like image 191
Dan Avatar answered Oct 05 '22 23:10

Dan