mask area outside a shapefile

조회 수: 2 (최근 30일)
Sourangsu Chowdhury
Sourangsu Chowdhury 2018년 10월 1일
답변: Hitesh 2025년 4월 1일

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
Vijay Sagar
Vijay Sagar 2023년 3월 24일
편집: Vijay Sagar 2023년 3월 24일
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.

댓글을 달려면 로그인하십시오.

답변 (1개)

Hitesh
Hitesh 2025년 4월 1일
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:

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by