Delete row from struct on string condition

7 Ansichten (letzte 30 Tage)
Martijn H
Martijn H am 27 Jan. 2018
Bearbeitet: Stephen23 am 28 Jan. 2018
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 28 Jan. 2018
Bearbeitet: Stephen23 am 28 Jan. 2018
You should simply use ismember:
idx = ismember({PaxUsage_struct.Country}, {'CY', 'EU27', 'EU28', 'LI', 'ME','MT'});
PaxUsage_struct = PaxUsage_struct(~idx);

Weitere Antworten (1)

Jan
Jan am 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.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by