only consider fields that exist within a structure

7 ビュー (過去 30 日間)
Alberto Acri
Alberto Acri 2023 年 6 月 16 日
移動済み: Stephen23 2023 年 7 月 19 日
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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by