Azzera filtri
Azzera filtri

Create an area mask using a shapefile

23 visualizzazioni (ultimi 30 giorni)
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);

Risposta accettata

Walter Roberson
Walter Roberson il 6 Set 2023
For polyshape objects use isinterior instead of inpolygon.
  9 Commenti
Walter Roberson
Walter Roberson il 9 Set 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;
Vidushi Koliyan
Vidushi Koliyan il 9 Set 2023
Thank you so much...

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by