inpolygon function within forloop help
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Randall Bonnell
le 24 Mai 2021
Commenté : Randall Bonnell
le 27 Mai 2021
Hi!
I am writing a script that reads in geolocated data, bins the data along a grid, and calculates the mean of the binned data for each grid cell. Essentially, I am wanting to create a raster, but the figure output suggests that I am not binning points in the correct location. If you wouldn't mind, could you take a look at my code and see if I am missing something? I've been working on this for a week now and still haven't made progress.
Thank you in advance!
%Before this code snippet, I load in variables from a csv file x, y, and t.
%x and y are locational data, t is time.
x_bin_edges = (234399:3:235602)';%Vector of x direction bin edges
y_bin_edges = flip(4325799:3:4327002)';%Vector of y direction bin edges
raster_mean = zeros(length(x_bin_edges)-1,length(y_bin_edges)-1);%Allocate a vector space
for i = 1:length(x_bin_edges)-1
for j = 1:length(y_bin_edges)-1
in = inpolygon(x,y,[x_bin_edges(i),x_bin_edges(i+1)],[y_bin_edges(j),y_bin_edges(j+1)]);
if sum(in) < 1%Output NaN's for grid cells that do not have any values.
raster_mean(i,j) = NaN;
elseif sum(in) > 0%Output the mean of the data (t) within the grid
raster_mean(i,j) = mean(t(in));
end
end
end
When I plot the data, I get the following:

As you can (hopefully) see, the red +'s are the plotted locations of the original data, whereas the colored grid cells is the plotted raster_mean calculated in the for loop. Not only do the data not line up, but the plot seems to suggest missing information.
6 commentaires
Réponse acceptée
Matt J
le 26 Mai 2021
I don't see anything wrong with your code, but this might be simpler:
m=numel(x_bin_edges)-1; n=numel(y_bin_edges)-1;
[~,~,~,binX,binY] = histcounts2(x,y,x_bin_edges,y_bin_edges);
raster_mean=accumarray([binX,binY],t,[m,n],@mean);
2 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Orange dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
