mask area outside a shapefile
10 views (last 30 days)
Show older comments
I am trying to mask data (lon,lat,data) outside a shape file, 'shp1'. I used top use arcgis for masking data but would prefer matlab for these actions.
the code below is non responsive
dx=d(:,:,1); %%%%d is a 80x80 data lat=(0:0.5:39.5)'; %%%%lat of the data lon=(60:0.5:99.5); %%%%lon of the data % lony=lony'; laty=repmat(lat,1,80); lony=repmat(lon,80,1); %%%%80x80 lon of the data laty=flipud(laty); %%%%80x80 lat of the data
%%%read shapefile
shp1=shaperead('C:\shpfiles\IND_adm0.shp');
lon1 = [shp1.X]';
lat1 = [shp1.Y]';
%%%mask try
rx = shp1.X(1:end-1);
ry = shp1.Y(1:end-1);
mask=inpolygon(lon1,lat1,rx,ry);
contourf(lon1,lat1,dx);
1 Comment
Vijay Sagar
on 24 Mar 2023
Edited: Vijay Sagar
on 24 Mar 2023
Your code is correct. Just replace in the last line lon1 and lat1 with lony and laty respectevely. Or you can use insidepoly or maskregion function.
Answers (1)
Hitesh
on 1 Apr 2025
Hi Sourangsu,
You need to create a mask that identifies points inside the polygon defined by the shapefile, and then apply that mask to your data. The issue with your code is related to how the "inpolygon" function is being used, as well as how the data is being plotted.
Kindly refer to this revised code and comments mentioned in the code:
% Load data
dx = d(:,:,1); % Assume d is a 80x80xN matrix
lat = (0:0.5:39.5)'; % Latitude values
lon = (60:0.5:99.5); % Longitude values
% Create grid of latitude and longitude
[lonGrid, latGrid] = meshgrid(lon, flipud(lat));
% Read the shapefile
shp1 = shaperead('sample_rectangle.shp');
rx = [shp1.X];
ry = [shp1.Y];
% Create a mask for points inside the polygon
inside = inpolygon(lonGrid, latGrid, rx, ry);
% Mask the data
maskedData = dx;
maskedData(~inside) = NaN; % Set points outside the polygon to NaN
% Plot the masked data
figure;
contourf(lon, flipud(lat), maskedData, 'LineColor', 'none');
xlabel('Longitude');
ylabel('Latitude');
title('Masked Data');
colorbar;
For more information regarding the "inpolygon" function, kindly refer to the following MATLAB documentation:
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!