Get cell array with childs from a cell array of identical structs

조회 수: 3 (최근 30일)
David
David 2020년 1월 17일
댓글: David 2020년 1월 17일
Dear Community,
I have the following problem. I have a cell array named "tags", each cell contains the same identical struct (please find .mat file attached). Each of this structs has two children "key" and "value" which are both strings (they could also be categorical as there is only a finite set of values).
Now I want to have a vector of indizes, telling me which of the cells contains a struct whos "value" child is equal to some querry string (e.g. water, forest).
Because my dataset it quite large I would like to solve this problem without for loops.
The problem is I don't know how to calculate a cell array containing the childs from a cell array containing structs which contain the childs.
Best regards,
David

채택된 답변

Guillaume
Guillaume 2020년 1월 17일
You're complicating your life by using a cell array to store scalar structures. Notwithstanding the extra memory used, it's an unnecessary level of indirection you don't need.
I would recommend converting that cell array into either a structure array or a table with actual strings (not char vectors) both of which are easier to use (table being the easiest).
Using a structure array:
tags = vertcat(tags{:}); %convert 1xN cell array of 1x1 structures with the same field into a Nx1 cell array.
%now find which elements of the structure have 'value' equal to something:
isforest = strcrmp({tags.values}, 'forest'); %logical vector. use find if you do need to convert it to indices. However logical vectors are often better.
Using a table of strings:
tags = struct2table(vertcat(tags{:})); %convert to structure then table
tags = convertvas(tags, 1:2, 'string'); %convert cell arrays of char vector into string array
isforest = tags.values == "forest"; %again use find if you need actual indices
  댓글 수: 1
David
David 2020년 1월 17일
Thanks! Using "vertcat" was exactly what I have been looking for.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Cell Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by