Create an area mask using a shapefile
26 views (last 30 days)
Show older comments
Vidushi Koliyan
on 6 Sep 2023
Commented: Vidushi Koliyan
on 9 Sep 2023
I am trying to mask my study area using a shapefile But unable to do so. Here is the code that i was trying.. I'll be really grateful if someone can help or provide me with some alternative method to achieve it.
Thank you so much.
% Load the data
load Data.mat
shapefile = 'India_shapefile.shp';
S = shaperead(shapefile);
polygon = polyshape([S.X], [S.Y]);
% Create a logical mask
logical_mask = inpolygon(lon, lat, polygon.Vertices(:, 1), polygon.Vertices(:, 2));
% Use the logical mask to extract data from matrix
extracted_data = grid_data(logical_mask);
0 Comments
Accepted Answer
Walter Roberson
on 6 Sep 2023
9 Comments
Walter Roberson
on 9 Sep 2023
% Load the data
load data.mat
shapefile = fullfile('India Shapefile', 'India_shapefile.shp');
S = shaperead(shapefile);
%remove small triangles and squares
coord_lengths = arrayfun(@(s) numel(s.X), S);
not_useful_mask = coord_lengths < 10;
S(not_useful_mask) = [];
polygon = polyshape({S.X}, {S.Y});
% Create a logical mask
[Lon, Lat] = meshgrid(lon, lat);
logical_mask = reshape(isinterior(polygon, Lon(:), Lat(:)), size(Lon));
% Use the logical mask to extract data from matrix
extracted_data = test_data(logical_mask);
subplot(3,1,1);
imagesc(lon, lat, test_data); title('data'); xlabel('lon'); ylabel('lat'); axis equal; set(gca, 'YDir', 'normal');
subplot(3,1,2);
plot(polygon); title('borders'); xlabel('lon'); ylabel('lat'); axis equal; set(gca, 'YDir', 'normal');
subplot(3,1,3);
imagesc(lon, lat, logical_mask); title('selected points'); xlabel('lon'); ylabel('lat'); axis equal; set(gca, 'YDir', 'normal');
You have to be careful with X and Y. Y is latitude, X is longitude, but you were passing in latitude (Y) into imagesc in the place it expects X coordinates. Also by default imagesc flips images, so we account for that.
Remember that extracted_data is going to be a vector, in the order that find() would report that logical_mask entries are true, which scans down columns. All of the true locations for one column will be extracted, then all of the true locations for the next column to the right, and so on. The code does not construct a "bounding box" or a convex hull. The extracted_data vector is generally not useful if you need to make any kind of spatial analysis. If you need to do something like contour the data within the bounds, then you would be better of doing something like
selected_data = test_data;
selected_data(~logical_mask) = nan;
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!