MATLAB Answers

How to filter a cell array filled with strings?

9 views (last 30 days)
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

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 4 Dec 2019
Edited: Adam Danz on 6 Dec 2019
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 Comment

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products


Release

R2019b