How can I remove all fields which start with a certain string?

조회 수: 8 (최근 30일)
Eli Borodach
Eli Borodach 2015년 10월 19일
답변: Eli Borodach 2015년 10월 19일
Hello all,
I have a struct which contains fields (for example):
shufling_significance_pos_slices_50
shufling_significance_pos_slices_25
shufling_significance_pos_slices_15
shufling_significance_pos_slices_10
shufling_significance_pos_slices_5
How can I remove all fields which start with 'shufling_significance_pos_slices'?
Thanks in advance

채택된 답변

Walter Roberson
Walter Roberson 2015년 10월 19일
prefix = 'shufling_significance_pos_slices';
fn = fieldnames(YourStructure);
tf = strncmp(fn, prefix, length(prefix));
newStructure = rmfield(YourStructure, fn(tf));

추가 답변 (2개)

Stephen23
Stephen23 2015년 10월 19일
편집: Stephen23 2015년 10월 19일
You would do much better do avoid naming the fields like this anyway. Confusing data and the abstract variables that represent them is the source of many bugs in beginners' programming. When you realize that 5, 10, etc are also data in their own right then your code will become a lot simpler.
Here is a discussion of why it is a bad idea to include meta-data (such as an index) in a variable name:
Then, once you realize that data does not belong in a variable name, simply create a non-scalar array and store all of your data in that:
S(1).index = 50;
S(2).index = 25;
S(3).index = 15;
S(4).index = 10;
S(5).index = 5;
S(1).shuffling_significance_pos_slices = ...
S(2).shuffling_significance_pos_slices = ...
.. etc
then to entirely remove any field/s from the entire structure it requires just one simple command rmfield:
S = rmfield(S,'shuffling_significance_pos_slices');
That is how easy using MATLAB can be when the data is organized well!

Eli Borodach
Eli Borodach 2015년 10월 19일
Thanks for both of you

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by