Adding a new field to a struct array
Show older comments
Hey All! I'm trying to add a new field to a struct array inline. I have the following struct:
A(1).name = 'bob';
A(2).name = 'cindy';
newstruct = 'address'
How do I go about adding the a field A.address to the array struct with the field name being define din the newstruct variable? The existing array should then look like the following:
A(1).name = 'bob';
A(2).name = 'cindy';
A(1).address = [];
A(2).address = [];
Accepted Answer
More Answers (2)
Siva
on 27 Jan 2018
1 vote
A(1).name = 'bob'; A(2).name = 'cindy'; A(1).address = ' Flat No.502, Apple Towers,... 1st line, Ravindra Nagar, Guntur,Andhra Pradesh, India,PIN-522006'; A(2).address = ' Flat No.102, Balaji Towers,... 2nd line, Brodipet, Guntur, Andhra Pradesh, India, PIN-522006';
sarah wentzel
on 23 Jan 2022
Edited: sarah wentzel
on 23 Jan 2022
1 vote
I created this cell
somecell = struct('Name', {'bob', 'lea', 'pat'}, 'Birth_year', {1990, 1988, 2021})
and now I want to add new information, favorite color. I know I can do it one by one like this:
somecell(1).color = 'blue'
somecell(2).color = 'red'
somecell(3).color = 'green'
But is there a way to do it with only one line? something like;
somecell (:,3).color = {'blue', 'red', 'green'}
thank you!
1 Comment
S = struct('Name', {'bob', 'lea', 'pat'}, 'Birth_year', {1990, 1988, 2021})
[S.color] = deal('blue','red','green')
Or from a cell array:
C = {'small', 'large', 'medium'};
[S.tshirtsize] = C{:}
Categories
Find more on Data Import from MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!