MATLAB Answers

How to mask a 3-D raster using a multiple feature attribute shapefile?

1 view (last 30 days)
Abhishek Chakraborty
Abhishek Chakraborty on 30 Apr 2021
Answered: Chad Greene on 2 May 2021
I wanted to mask a raster file using a shapefile which contains more than one feature attributes. For shapefile containing only one feature attribute, it can be done like this:
A=geotiffread('A.tif'); %This is the 3-D raster of dimension 720x360x1320 where 1320 is the time dimension and 720 and 320 are the lon and lat, respectively
info = geotiffinfo('A.tif');
[x,y]=pixcenters(info); % x is Lon and y is Lat
[X,Y] = meshgrid(x,y);
roi = shaperead('shapefile.shp'); %This is the shapefile which contains only 1 feature attribute
% Remove trailing nan from shapefile
rx = roi.X(1:end-1);
ry = roi.Y(1:end-1);
mask = inpolygon(X,Y,rx,ry);
mask=double(mask); %Convert logical to double
But when I am trying the same with a shapefile containing multiple feature attributes, I am getting this error:
A=geotiffread('A.tif'); %This is the 3-D raster of dimension 720x360x1320 where 1320 is the time dimension and 720 and 320 are the lon and lat, respectively
info = geotiffinfo('A.tif');
[x,y]=pixcenters(info); % x is Lon and y is Lat
[X,Y] = meshgrid(x,y);
roi = shaperead('shapefile.shp'); %This is the shapefile which contains multiple feature attributes
% Remove trailing nan from shapefile
rx = roi.X(1:end-1);
ry = roi.Y(1:end-1);
mask = inpolygon(X,Y,rx,ry);
Expected one output from a curly brace or dot indexing expression, but there were 36 results.
There were actually 36 different feature attributes in the second shapefile. Let us suppose I want to extract the area of raster which has field number (featute attribute) 10 in the shapefile, then how to do it?

Answers (1)

Chad Greene
Chad Greene on 2 May 2021
Try this:
mask = inpolygon(X,Y,[roi.X],[roi.Y]);
You don't even need to remove the trailing nans. :)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!