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

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by