Effacer les filtres
Effacer les filtres

only consider fields that exist within a structure

5 vues (au cours des 30 derniers jours)
Alberto Acri
Alberto Acri le 16 Juin 2023
Déplacé(e) : Stephen23 le 19 Juil 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 commentaires
Paul
Paul le 16 Juin 2023
Hi Alberto,
Why do you want to extract the data from the struct into individual variables this way?
Stephen23
Stephen23 le 17 Juin 2023
Déplacé(e) : Stephen23 le 19 Juil 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:

Connectez-vous pour commenter.

Réponse acceptée

Voss
Voss le 16 Juin 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

Plus de réponses (0)

Catégories

En savoir plus sur Structures dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by