Filter a struct based on the field name.

46 ビュー (過去 30 日間)
Ubaldo
Ubaldo 2016 年 7 月 28 日
回答済み: Stephen23 2016 年 7 月 28 日
Hi all. Assume that i have a struct like the following
my_struct:
f1_x : 0
f1_y : 1
f1_z : 3
f2_x : -1
f2_y : 2
f3_y : 0
My question is how to filter based on the field name (of better, based on part of the field name). For example, if I want to filter all the fields that start with the string f1_, thus obtaning
my_struct_f1:
f1_x : 0
f1_y : 1
f1_z : 3
what should I do? Many thanks in advance.

採用された回答

Adam
Adam 2016 年 7 月 28 日
編集済み: Adam 2016 年 7 月 28 日
names = fieldnames( myStruct );
subStr = 'f1_';
filteredStruct = rmfield( myStruct, names( find( cellfun( @isempty, strfind( names , subStr ) ) ) ) );
should work, based on a quick test, though there may be more efficient methods.
  1 件のコメント
Ammar Dodin
Ammar Dodin 2016 年 7 月 28 日
I also tried what Adam suggested above and it works.

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

その他の回答 (2 件)

Ammar Dodin
Ammar Dodin 2016 年 7 月 28 日
編集済み: Ammar Dodin 2016 年 7 月 28 日
For simplicity, let's assume that your struct's name is S. You can first get the field names of struct S using fieldnames. After that you can use something like regex to capture all the filed names that match your criteria.
names = fieldnames(S);
match = {};
for i = 1:length(names)
if ~isempty(regexp(names{i},'^f1')
match{end+1} = names{i};
end

Stephen23
Stephen23 2016 年 7 月 28 日
Rather than using a scalar structure and messy code with fieldnames, a far more efficient and simple approach is to use a non-scalar structure:
S(1).x = 0;
S(1).y = 1;
S(1).z = 3;
S(2).x = -1;
S(2).y = 2;
S(3).y = 0;
and get the first element:
>> S(1)
ans =
x: 0
y: 1
z: 3
See how easy MATLAB can be ?

カテゴリ

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