only consider fields that exist within a structure

5 次查看(过去 30 天)
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 个评论
Paul
Paul 2023-6-16
Hi Alberto,
Why do you want to extract the data from the struct into individual variables this way?
Stephen23
Stephen23 2023-6-17
移动:Stephen23 2023-7-19
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:

请先登录,再进行评论。

采纳的回答

Voss
Voss 2023-6-16
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 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by