Delete row from struct on string condition
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all, I try to remove rows from a dataset structure based on a condition in a string. I converted a cell array to a structure. The first field of the structure is 'Country', here country codes are listed as strings. The other 12 columns contain numbers (doubles) of railway usage during the last years. Now I want to delete rows from the structure that have a specific countrycode (because the other dataset (ie. length of railwaylines) doesn't have data for that country). However I can't seem that to work. Country codes that need to be deleted: 'CY', 'EU27', 'EU28', 'LI', 'ME' and 'MT'.
For example for the country 'CY' I tried this:
for i = 1:size(PaxUsage_struct,2)
if isequal(PaxUsage_struct(i).Country,'CY')
PaxUsage_struct(i) = []
end
end
However the code
isequal(PaxUsage_struct(i).Country,'CY')
does seem to work, when I type it in the command window myself (with i = 6) it returns 1, with i = 5 it returns 0. So now row 6 needs to be removed. So why does the removing not work?
Running the script does not return an error, just nothing changes in the structure.
0 commentaires
Réponse acceptée
Plus de réponses (1)
Jan
le 27 Jan 2018
This is a bad idea:
for i = 1:size(PaxUsage_struct,2)
if isequal(PaxUsage_struct(i).Country,'CY')
PaxUsage_struct(i) = []
end
end
Imagine the PaxUsage_struct(2) is removed. Then PaxUsage_struct is shorter and the loop will fail, when it runs until the original size(PaxUsage_struct,2). Better:
toRemove = strcmp({PaxUsage_struct.Country}, 'CY');
PaxUsage_struct(toRemove) = [];
I cannot follow your explanations concerning "does seem to work". Please provide some test data or use the debugger to examine this by your own.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!