add a new field to structure

183 visualizaciones (últimos 30 días)
Majid Al-Sirafi
Majid Al-Sirafi el 4 de Dic. de 2013
Editada: Stephen23 el 19 de Dic. de 2017
Hi all friends
I have a structure variable; this variable is defined as follows:
Student structure; consists of the following fields
Name
Age
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

Respuesta aceptada

Wayne King
Wayne King el 4 de Dic. de 2013
Editada: Wayne King el 4 de Dic. de 2013
teststruct = struct('names',{'bob','dave','sara'});
% now add field called data
[teststruct(:).data] = deal(randn(3,1));
fieldnames(teststruct)
  2 comentarios
Kyle Wright
Kyle Wright el 19 de Dic. de 2017
Editada: Kyle Wright el 19 de Dic. de 2017
Is this answer working as intended?
I would assume that you used...
deal(randn(3,1))
...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.
Stephen23
Stephen23 el 19 de Dic. de 2017
Editada: Stephen23 el 19 de Dic. de 2017
C = num2cell(randn(3,1));
[teststruct(:).data] = deal(C{:})
How this works is explained in the MATLAB documentation:

Iniciar sesión para comentar.

Más respuestas (1)

Majid Al-Sirafi
Majid Al-Sirafi el 4 de Dic. de 2013
thank you sir, that is I want
best regards

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by