How to extract the right struct from the cell array of structs based on condition?

2 ビュー (過去 30 日間)
Nazar Adamchuk
Nazar Adamchuk 2022 年 6 月 28 日
回答済み: Chunru 2022 年 6 月 28 日
have a 4x1 cell array that looks like in the attached file.
load('part.mat');
searchedItem = struct();
for k = 1:length(values)
TF = isfield(values{k},{'property'});
if TF == 1
if convertCharsToStrings(values{k}.property) == "Mass %"
searchedItem = values{k};
end
end
end
I need to extract the struct with the fieldname Mass %. (not all of the structs have a fieldname property). What is the MATLAB-ish way to do it avoiding the loops? In my original file I have to deal not with 4x1 cell array but 200+.

採用された回答

Chunru
Chunru 2022 年 6 月 28 日
load part.mat
whos
Name Size Bytes Class Attributes ans 1x33 66 char cmdout 1x33 66 char values 4x1 46794 cell
% MATLAB-ish way
idx = cellfun(@(x) isfield(x, 'property') && x.property == "Mass %", values);
searchedItem = values(idx)
searchedItem = 1×1 cell array
{1×1 struct}
searchedItem{1}
ans = struct with fields:
x_id: '602d50842dfa5b802aa64cdd' itemid: '602d50842dfa5b802aa64cde' db_version: 30 permission_group: 'allreadonly' view_id: {'602d50842dfa5b802aa64cde'} modifiedby: 'beckerpe' visible_: 'all' array: {2×1 cell} sectags: {'Chemical Composition'} valuetype: 'array' value: {8×1 cell} child_: 1 lastsaved: '2021-02-17 17:21:08.014607' version: 1 attributes: [3×1 struct] property: 'Mass %' type: 'attribute'

その他の回答 (0 件)

カテゴリ

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