Delete row from struct on string condition
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Più risposte (1)
Jan
il 27 Gen 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 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!