Some shapefile utilities for Matlab (and data transfer to Stata)

Here are some extremely simple but extremely useful functions when working with shapefiles in Matlab.

Functions to drop or keep polygons in your workspace based on their attributes (drop_by_attribute.m, keep_by_attribute.m).

A simple command to plot all your polygons (plot_districts.m).

A Matlab function to merge attributes (combine_attributes.m) and an accompanying Stata function to "un-merge" those attributes (break_var.ado).  This is particularly useful if you want a single attribute to uniquely identify a polygon (eg. combining State and County into a single attribute State_County) which you use when you do some calculations in Matlab (eg. compute avg. temperature by State_County) and export to Stata (using my scripts here) where you then want to retrieve the original distinct attributes (eg. State and County) for statistical analysis.

Example usage:

(in Matlab)

[s, a] = shaperead('YourShapeFile.shp', 'UseGeoCoords', true) % read in file with mapping toolbox

plot_districts(s) % look at your shapefile

[s, a] = drop_by_attribute(s, a, 'State', 'Alaska')  % drop all counties in Alaska

a2 = combine_attributes(a, 'State', 'County') % combines attributes to make a new variable State_County

...do calculations that you export to Stata...

(in Stata)

break_var State_County, first(State) second(County) % regenerates the two original variables


  1. Hi,

    I have a question here.....

    Can we perform morphological operations on these shapefiles? like dilation, erosion, opening and closing?

    1. These are just some utilities for manipulating shapefiles in Matlab, but there are many built in functions that you could use in the Matlab's mapping toolbox. Or you can write scripts to do these various operation.