structure contains multiple cells with different variables in them I would like to remove variables not present in all cells

2 ビュー (過去 30 日間)
my structure (data) contains 1x3 cells horizontally. Each cell inturn contains three 1x1 structures with about 165 variables in each of them (The number of variables is not constant). I am trying to compare all variables names within these cells and then remove variables not present in all cells. This is so I can concatinate all the variables within these cells hoizontally. Below is a piece of code I have written to identify all the fieldnames from a structure called data and then concatenate them vertically. problem arises when there are missing variables, which I would then like to remove if not found on all cells within data.
flds = fieldnames(data{1,1});
for f = 1:size(flds,1)
out(f,:) = eval(['[data{1,1}.', flds{f} ,' ', 'data{1,2}.', flds{f} ,' ', 'data{1,3}.', flds{f} ,']']);
end
  2 件のコメント
Stephen23
Stephen23 2019 年 11 月 12 日
Rather than using awful anti-pattern eval, you should simply use dynamic fieldnames:
Please upload sample data by clicking the paperclip button.
Mithilesh Rajendrakumar
Mithilesh Rajendrakumar 2019 年 11 月 12 日
Hi Stephen,
Thanks for your inputs. Will definitely look into the link you provided but I am afraid I will not be able to upload sample data since it is confidential information.
Thanks Again!

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

採用された回答

Guillaume
Guillaume 2019 年 11 月 12 日
編集済み: Guillaume 2019 年 11 月 12 日
%identify common fields
commonfields = fieldnames(data{1});
for cidx = 2:numel(data)
commonfields = intersect(commonfields, fieldnames(data{cidx}));
end
%keep only the common fields in each structure
trimmeddata = cell(size(data));
for cidx = 1:numel(data)
scell = struct2cell(data{cidx}); %convert to cell for easy extraction
[tokeep, fieldindex] = ismember(fieldnames(data{cidx}), commonfields); %which rows of cell array to keep and which order to use for commonfields
trimmeddata{cidx} = cell2struct(scell(tokeep, :), commonfields(fieldindex(tokeep)), 1); %convert back into structure
end
merged = [trimmeddata{:}];
  3 件のコメント
Guillaume
Guillaume 2019 年 11 月 12 日
Fixed, I'd forgotten to remove the indices (0) of fields to discard from fieldindex.
Mithilesh Rajendrakumar
Mithilesh Rajendrakumar 2019 年 11 月 13 日
Thanks a Ton Guillaume! Worked like a charm!

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by