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

9 次查看(过去 30 天)
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