Searching cell array with regex
I often find myself trying to search cell arrays like I would want to search a database with a sql query. In this case, I've got a number of military bases (bases.shp)
bases = shap开发者_JS百科eread('us-military-bases.shp')
and then I want to filter down the shape file to get Air Force bases, something like regexp({bases.FAC_NAME}','Air Force')
. But the output I get is the fairly cumbersome:
[]
[]
[ 4]
[]
[]
[ 9]
[]
I am sure filtering down cell arrays or shapefiles is pretty common and there have to be some good practices. Thanks for any insight.
I am also trying things like:
trif = arrayfun(@(x)regexp(x.FAC_NAME,'Griff','match'),af_bases)
Given the output of regexp
you can index back into the original cell array just by checking if each item in the resultant cell array is empty. You can do this using cellfun
to apply a function to each cell.
To get an array of logicals, for non-empty items you can do:
base_strings = {bases.FAC_NAME}';
ind = ~cellfun(@isempty, regexp(base_strings, 'Air Force'))
Or more cleanly using an anonymous function:
ind = cellfun(@(x)( ~isempty(x) ), regexp(base_strings, 'Air Force'))
Then, to filter:
filtered = base_strings(ind);
精彩评论