Delete row from struct on string condition
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!