フィルターのクリア

Checking if a nested field exists in a structure

8 ビュー (過去 30 日間)
KAE
KAE 2020 年 4 月 28 日
編集済み: KAE 2020 年 5 月 15 日
I am building a structure whose fields and subfields are nested structures. I would like to cycle through a subfield, determine if any values have been assigned yet, and if not, assign a value to the end of an array. Here is an example in which I am checking how many potato dishes guests are bringing to a potluck Thanksgiving dinner. Is there a better way to do this? My real dataset has many more fields than this example.
potatoList = {'Yam', 'White', 'Candied'};
for iPerson = 1:4 % cycle through guests
for iPotato = 1:length(potatoList)
isFirst = false; % Is this the first entry for a given type of potato or not?
if ~exist('Thanksgiving', 'var') % Haven't even created the structure yet
isFirst = true;
else % Structure exists, but subfield may not
if ~isfield(Thanksgiving, 'Potato')
isFirst = true;
else
if ~isfield(Thanksgiving.Potato, potatoList{iPotato})
isFirst = true;
end
end
end
if isFirst
iValue = 1; % The first time, the index starts at one
% Placeholder for nested subfield before value is assigned, to avoid
% error due to field not existing yet
Thanksgiving.Potato.(potatoList{iPotato}).number = [];
else
% After the first time, the index starts at the end of the array
iValue = length(Thanksgiving.Potato.(potatoList{iPotato}).number) + 1;
end
% Assign example values to array
Thanksgiving.Potato.(potatoList{iPotato}).number(iValue) = ...
round(rand(1)*10); % Number of potato dishes someone is bringing
end
end

回答 (1 件)

rajat aggarwal
rajat aggarwal 2020 年 5 月 13 日
You can use indexing to access the fields of data structure. Some people have also developed some API for accessing data structure in MATLAB.
You can also generate field names from variables. Please refer to following link for more information.
https://www.mathworks.com/help/matlab/matlab_prog/generate-field-names-from-variables.html
It is not clear from code that what fields and data fields are present in your potato structure. If you need more inputs on this, Please share your structure details.
  1 件のコメント
KAE
KAE 2020 年 5 月 14 日
編集済み: KAE 2020 年 5 月 15 日
You should be able to run the code I provided to generate an example structure with many nested fields. In the code, I have to check if a subfield does not exist yet (isFirst = true) and assign an empty placeholder value [] before assigning numerical values. I am wondering if there is a better way.
If my question is still unclear please let me know.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by