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

9 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Walter Roberson
Walter Roberson il 19 Ott 2015
prefix = 'shufling_significance_pos_slices';
fn = fieldnames(YourStructure);
tf = strncmp(fn, prefix, length(prefix));
newStructure = rmfield(YourStructure, fn(tf));

Più risposte (2)

Stephen23
Stephen23 il 19 Ott 2015
Modificato: Stephen23 il 19 Ott 2015
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 il 19 Ott 2015
Thanks for both of you

Categorie

Scopri di più su Structures in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by