Extract data from a matrix for each polygon in a shape file

I have a matrix (331X301) at 0.1 degree resolution data encompassing entire India and a shapefile with 2299 attributes(polygons). I generally extarct data for each attribute from the matrix raster in ArcGIS. Is there a way to extract the mean data(mean of all the 0.1 degree grids that fall in that attribute) for all the polygons of the shpfile in Matlab?
Note: the data is 3 dimension-331x301x12.
Below is the code written to overlay the shapefile on the data.
However, the shapefile S has 2299 attributes, I could not extract value of z2 for each of these 2299 attributes
Reading the shapefile
S=shaperead('C:\shpfiles\india_adm3.shp');
%selecting the first month from the data of 321x321x12
z2= data(:,:,1)
%makking dummy coordinates for the data
x = linspace(67, 97, 301);
y = linspace(5, 38, 331);
[x,y] = meshgrid(x,y);
y=flipud(y);
%Clipping the data to the coastlines
isin = inpolygon(x,y,S.X,S.Y);
z2(~isin) = NaN;
figure('color','w');
mx=geoshow('landareas.shp', 'FaceColor', 'White');
%display the data
contourf(x,y,z2,'LineColor','none');
hold on
%display the shapefile
S1=shaperead('C:\shpfiles\india_adm3.shp','Attributes',{'BoundingBox'});
lon1 = [S1.X]';
lat1 = [S1.Y]';
plot(lon1,lat1,'Linewidth',2,'color',[0 0 0]);

 Accepted Answer

Read about inpolygon.

7 Comments

Hi @KSSV, I tried using inpolygon ,
but the output S is a struct of 2299x1, so it returns an error
%Clipping the data to the coastlines
isin = inpolygon(x,y,S.X,S.Y);
z2(~isin) = NaN;
however, if I use a shapefile with no other inset polygons, this code works fine
shapefile conains many polygons....you need to run a loop for each polygon.
isin = inpolygon(x,y,S(i).X,S(i).Y);
See to it that..you have closed polygon coordinates in hand.
for i=1:2299;
isin = inpolygon(x,y,S(i).X,S(i).Y);
z2 = z;
z2(~isin) = NaN;
xf=nanmean(nanmean(z2,2),1);
cx(i)=xf
end;
ok, I was able to get the desired results, with the following @KSSV;
thank you so much,
just inquiring, is there a way to add facecolor to each of these polygons as per the values of cx and plot it?
as an extension to the previous code, I wrote
for ii = 1:numel(S)
S(ii).cx = cx(ii); % add your data here
end
to add cx as a feature to the existing shapefile. I now need to display the shapefile with one distinct color (of a colormap like jet) for each polygon within the shapefile
h = geoshow(S);
set(h.Children, {'CData'}, {S.cx}');
set(h.Children, 'Facecolor', 'flat');
I tried with the following code, but it returns an error,
Error using matlab.graphics.primitive.Patch/set
Value cell array handle dimension must match handle vector length.
figure
hold on
for i = 1:N
x = S(i).X ;
y = S(i).Y ;
patch(x,y,rand(1,3))
end

Sign in to comment.

More Answers (0)

Asked:

on 22 Jan 2019

Commented:

on 22 Jan 2019

Community Treasure Hunt

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

Start Hunting!