[matlab] modifying/manipulating shapefile (.shp) contents

Before you start reading:

  1. You should check if “Mapping Toolbox” is installed in your MATLAB first. You can check it by typing “ver” command on your MATLAB “Command Window”.
  2. I’m using MATLAB r2014a to test the code
  3. I’m using this SHP file: Shapefile for Polewali Mandar

Adding new field/attribute to the shapefile
Actually, until now, I don’t know how to do it using MATLAB alone. As you know, a shapefile (.shp) doesn’t stand alone, there always be some other files with the same name but different extension. The one we need if we want to add a new attribute/field into the shapefile is the file with .DBF extension. Yup, it’s just DBASEIII+ file. Usually I use LibreOffice Calc to open the .DBF file and then adding the new field as new column and save it back as .DBF file. See screenshot:

Adding new attribute/field via LibreOffice Calc

Adding new attribute/field via LibreOffice Calc

As you can see, I add new attribute, i.e. ‘KELAS’ which is character type field (‘C’) and has 11 in length.
You can always use specialized GIS apps to do this (such as QGIS) but I don’t have it on my working PC, so I just grab whatever I have. 😀

Opening a shapefile
as simple as this:

s=shaperead('polman'); % this will open POLMAN.shp and assign it to 's' variable

Deleting/removing attribute from shapefile
Use these code sequences:

spec=rmfield(spec, 'KELAS'); % let's delete KELAS attribute
shapewrite(s, 'new_polman', 'DbfSpec', spec); % save it to new shapefile (new_polman.shp) incase you want to keep the original

Finding object inside shapefile based on it’s attribute value
something like these:

dx=find(cellfun(@(x)strcmpi(x,'ALU'),{s.KECAMATAN})); % find all objects that 'KECAMATAN' attribute value is 'ALU'
% now, 'dx' will contain all object indexes that match the search criterion

Edit and save back the attribute value
An example:

s(33).KELAS='SANGAT LUAS'; % change the 'KELAS' attribute value of object number 33
shapewrite(s, 'polman'); % save the changes!

Viewing the shapefile interactively
Use the built-in interactive viewer:


It will open a new MapView window where you can import the shapefile from workspace variable or via opening the file directly.

MAPLAB's mapview

MAPLAB’s mapview

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>