How to filter a cell array filled with strings?

21 ビュー (過去 30 日間)
Maximilian Stopfer
Maximilian Stopfer 2019 年 12 月 4 日
編集済み: Stephen23 2024 年 4 月 12 日 11:39
Dear all,
I have a dataset with 576 cells [1x576] and all cells contain strings [1x1 struct]. These strings contain two colums (field, value), e. g.:
A01 = struct('a',1,'b',2,'c',0)
A02 = struct('a',0,'b',2,'c',1)
A03 = struct('a',2,'b',2,'c',0)
A04 = struct('a',0,'b',1,'c',1)
A05 = struct('a',1,'b',0,'c',2)
A = {A01,A02,A03,A04,A05}
How can I filter all cells with a specific field name and extract them (as example: how can I filter all structs with a=1 and save the b values in new array)?
Sincerely yours, Max
  1 件のコメント
Stephen23
Stephen23 2024 年 4 月 12 日 10:51
編集済み: Stephen23 2024 年 4 月 12 日 11:39
Storing lots of scalar structures in a cell array is inefficient data design, which leads to inefficient code.
Assuming that all of the scalar structures have the samew fields (as your example shows), then much better data design would be to use one non-scalar structure array:
A = struct('a',{1,0,2,0,1},'b',{2,2,2,1,0},'c',{0,1,0,1,2})
A = 1x5 struct array with fields:
a b c
This has more efficient memory and access, as well as offering some convenient syntaxes for accessing the data:

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

採用された回答

Adam Danz
Adam Danz 2019 年 12 月 4 日
編集済み: Adam Danz 2019 年 12 月 6 日
This will return a logical array the same size as 'A' where TRUE values indicate elements of A that meet the following requirements:
  • A{i} is a structure
  • A{i} contains a field named 'a'
  • The value of field 'a' is equal to 1
keyField = 'a';
keyValue = 1;
idx = cellfun(@(s)isstruct(s) && any(strcmp(fieldnames(s),keyField)) && isequal(s.(keyField),keyValue), A)
To filter those structures from the cell array A,
A(idx)
  1 件のコメント
Maximilian Stopfer
Maximilian Stopfer 2019 年 12 月 6 日
It works perfectly.
Thanks a lot!

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by