Delete row from struct on string condition

7 ビュー (過去 30 日間)
Martijn H
Martijn H 2018 年 1 月 27 日
編集済み: Stephen23 2018 年 1 月 28 日
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.

採用された回答

Stephen23
Stephen23 2018 年 1 月 28 日
編集済み: Stephen23 2018 年 1 月 28 日
You should simply use ismember:
idx = ismember({PaxUsage_struct.Country}, {'CY', 'EU27', 'EU28', 'LI', 'ME','MT'});
PaxUsage_struct = PaxUsage_struct(~idx);

その他の回答 (1 件)

Jan
Jan 2018 年 1 月 27 日
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by