only consider fields that exist within a structure
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Alberto Acri
el 16 de Jun. de 2023
Hello! I have a mystruct structure. Within this struct I have several fields to consider (for example: data, number, variable, row, column) and from which I go to extract the respective value in the following way:
data = mystruct.data;
number = mystruct.number;
variable = mystruct.variable;
row = mystruct.row;
column = mystruct.column;
Since I want to use the same code for multiple structs, how can I exclude some fields from the calculation in case they do not exist within the struct ?
For example: if there are no row and column fields in mystruct_1, how can I write the code above so that it does not consider them? Like, "If the row field and column field exist then calculate the value, otherwise not".
data = mystruct_1.data;
number = mystruct_1.number;
variable = mystruct_1.variable;
if % row and column exist
row = mystruct_1.row;
column = mystruct_1.column;
end
Thank you
2 comentarios
Paul
el 16 de Jun. de 2023
Hi Alberto,
Why do you want to extract the data from the struct into individual variables this way?
Stephen23
el 17 de Jun. de 2023
Movida: Stephen23
el 19 de Jul. de 2023
Generally it is easier to keep data together, rather than split it apart. Do not "extract" all of the fields to separate variables. Instead just get the fieldnames and fielddata, then loop over the fieldnames and decide what you need to do with the data, e.g.:
F = fieldnames(S)
C = struct2cell(S)
for k = 1:numel(F)
A = C{k}
switch F{k}
case 'data'
..
case 'number'
..
..
otherwise
error(..)
end
end
With a little bit of thought you can also sort them into particular order (hint: ISMEMBER, logical indexing), should that be required. Ignoring particular fields is also easy.
Or perhaps a table might be a better data container, try STRUCT2TABLE, there are many tools for processing table data:
Respuesta aceptada
Voss
el 16 de Jun. de 2023
Use isfield.
if isfield(mystruct_1,'row') && isfield(mystruct_1,'column') % row and column exist
row = mystruct_1.row;
column = mystruct_1.column;
end
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!