Clear Filters
Clear Filters

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

1 view (last 30 days)
have a 4x1 cell array that looks like in the attached file.
searchedItem = struct();
for k = 1:length(values)
TF = isfield(values{k},{'property'});
if TF == 1
if convertCharsToStrings(values{k}.property) == "Mass %"
searchedItem = values{k};
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+.

Accepted Answer

Chunru on 28 Jun 2022
load part.mat
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') && == "Mass %", values);
searchedItem = values(idx)
searchedItem = 1×1 cell array
{1×1 struct}
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'

More Answers (0)


Find more on Structures in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!