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