How to get the area of a shapefile with bounding box

27 ビュー (過去 30 日間)
Ariana
Ariana 2023 年 5 月 9 日
コメント済み: LeoAiE 2023 年 5 月 11 日
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!

回答 (1 件)

LeoAiE
LeoAiE 2023 年 5 月 10 日
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 件のコメント
Ariana
Ariana 2023 年 5 月 10 日
Thank you that really helped! So to get each polygon's area I would change my i from 1=1:n to i=2:n and so on?
LeoAiE
LeoAiE 2023 年 5 月 11 日
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

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMap Display についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by