subha
subha

Reputation: 65

How to add new field to an non-empty struct in Matlab?

I have a 1-by-565 struct array, GRID, where each struct has five fields:

A
B
C
D
E

Each field has some value and now I need to add a sixth field, G, to every element in GRID. I tried:

GRID(:).G=addfield(G,[])
GRID(:).G=[]

but that doesn't work. What I need is for GRID(1) to yield

A
B
C
D
E
G

where each has a double value assigned to it.

Upvotes: 0

Views: 351

Answers (2)

Suever
Suever

Reputation: 65460

You can just assign an empty array to the new field of the last element of the array of structs.

Since you have an array of structs, MATLAB will automatically add this field to all other structs in the array and set it equal to the default value ([])

GRID(end).G = [];

Upvotes: 1

AVK
AVK

Reputation: 2149

You can use deal:

[GRID(:).G]=deal([])

Upvotes: 1

Related Questions