MATLAB Answers


add a new field to structure

Asked by Majid Al-Sirafi on 4 Dec 2013
Latest activity Edited by Stephen Cobeldick on 19 Dec 2017
Hi all friends
I have a structure variable; this variable is defined as follows:
Student structure; consists of the following fields
Suppose that I fill it with data (for example five students)
Later I want to add another field (for example degree field) to student structure
How can I do that and fill the degree field with data
Please help me


Sign in to comment.



2 Answers

Wayne King 님의 답변 4 Dec 2013
Wayne King 님이 편집함. 4 Dec 2013
 채택된 답변

teststruct = struct('names',{'bob','dave','sara'});
% now add field called data
[teststruct(:).data] = deal(randn(3,1));


Is this answer working as intended?
I would assume that you used...
...using a "3" so that it would match the length of the struct as it is. However, this code puts the 3x1 array into EACH of the (.data) fields, rather than distributing one of each of the vector to one of each of the (.data) fields.
C = num2cell(randn(3,1));
[teststruct(:).data] = deal(C{:})
How this works is explained in the MATLAB documentation:

Sign in to comment.

Answer by Majid Al-Sirafi on 4 Dec 2013

thank you sir, that is I want
best regards


Sign in to comment.