# How to get the area of a shapefile with bounding box

30 Ansichten (letzte 30 Tage)
Ariana am 9 Mai 2023
Kommentiert: LeoAiE am 11 Mai 2023
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 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Antworten (1)

LeoAiE am 10 Mai 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.
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 KommentareKeine anzeigenKeine ausblenden
Ariana am 10 Mai 2023
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 am 11 Mai 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

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Data Import and Export finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by