Filter löschen
Filter löschen

only consider fields that exist within a structure

5 Ansichten (letzte 30 Tage)
Alberto Acri
Alberto Acri am 16 Jun. 2023
Verschoben: Stephen23 am 19 Jul. 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 Kommentare
Paul
Paul am 16 Jun. 2023
Hi Alberto,
Why do you want to extract the data from the struct into individual variables this way?
Stephen23
Stephen23 am 17 Jun. 2023
Verschoben: Stephen23 am 19 Jul. 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:

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Voss
Voss am 16 Jun. 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

Weitere Antworten (0)

Kategorien

Mehr zu Structures finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by