How to get the area of a shapefile with bounding box
34 views (last 30 days)
Show older comments
Hi, I'm new to coding and don't know where to start. I have made a shapefile on ArcGIS and imported it using the shaperead function. I got back the geometry type, bounding boxes, X, Y, and identifiers I added in the original attribute table. How do I use the boundingbox to find the area of my shapefiles?
Thank you!
0 Comments
Answers (1)
LeoAiE
on 10 May 2023
To calculate the area of your shapefiles, you can use the polyarea function in MATLAB. Since you have the bounding box, you can use the coordinates of the bounding box to create a polygon, and then calculate the area of the polygon.
S = shaperead('your_shapefile.shp');
n = length(S);
areas = zeros(n, 1);
for i = 1:n
% Get the bounding box
bbox = S(i).BoundingBox;
% Extract the corner coordinates
x1 = bbox(1, 1);
y1 = bbox(1, 2);
x2 = bbox(2, 1);
y2 = bbox(2, 2);
% Create a polygon from the bounding box
X = [x1, x1, x2, x2];
Y = [y1, y2, y2, y1];
% Calculate the area of the polygon
areas(i) = polyarea(X, Y);
end
Please note that this will give you the area of the bounding box, not the exact shape. If you need to calculate the area of the exact shape, you can use the areaquad function from the Mapping Toolbox for a more accurate result (assuming your shapes are polygons):
n = length(S);
areas = zeros(n, 1);
for i = 1:n
% Get the X and Y coordinates of the polygon
X = S(i).X;
Y = S(i).Y;
% Remove the NaN value at the end of the coordinates
X = X(1:end-1);
Y = Y(1:end-1);
% Calculate the area of the polygon using areaquad (assumes geographic coordinates)
area = 0;
for j = 1:length(X)-1
area = area + areaquad([Y(j), X(j)], [Y(j+1), X(j+1)], [Y(j+1), X(j)], [Y(j), X(j+1)]);
end
areas(i) = area;
end
2 Comments
LeoAiE
on 11 May 2023
Yes, that's correct! To obtain the area of each polygon, you can loop through the polygons from 1 to n (where n is the total number of polygons) and call the polyarea function for each one.
% Assuming 'S' is the shapefile structure array obtained from shaperead()
n = numel(S); % Number of polygons
areas = zeros(1, n); % Preallocate an array to store the areas
for i = 1:n
X = S(i).X;
Y = S(i).Y;
% Remove the NaN separator for multipart polygons
X(isnan(X)) = [];
Y(isnan(Y)) = [];
areas(i) = polyarea(X, Y);
end
See Also
Categories
Find more on Map Display in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!