Counts in bins for 2D histogrsm using nested for loop ?

1 次查看(过去 30 天)
I am trying to write extend 1D histogram code to 2D histogram, after creating bins using mesh grid
how to count if data point x,y is in the bin?
%1D code
A = [1 ;1 ;2 ;2 ;2 ;4 ;4 ;4 ;4 ;4 ;4 ;5 ;5 ;6 ;1 ];
A_u = unique(A);
z = zeros(size(A_u));
for i = 1:length(A_u)
z(i) = sum(A_u(i)==A); %Counts the frequency, need something similar for 2D
end
z = [A_u, z];
%2D code
x = [1,2,5,6,7,3,4,9,5,2,8]';
y = [1,1,3,6,4,3,6,5,8,7,4]';
xy = [x,y];
mn_x = min(x);
mx_x = max(x);
mn_y = min(y);
mx_y = max(y);
x_rng = linspace(mn_x,mx_x,3);
y_rng = linspace(mx_y,mn_y,3);
[p,q] = meshgrid(x_rng,y_rng);
z = zeros(size(p,1),size(q,2));
for i = 1:size(p,1)
for j = 1:size(q,2)
%Need help here to decide criteria, like 1D histogram,
problem is I cant access all elements of xy as counters for loops goes
through rows and columns of p and q.
z(i,j) = sum( (p(i) < xy(:,1) < p(i+1,:)) & (q(j) < xy(:,2) < q(j+1,:)) );
end
end

回答(1 个)

the cyclist
the cyclist 2016-2-6
If you have a relatively recent version of MATLAB, you could have gotten the 1-d counts using the histcounts command:
A = [1 ;1 ;2 ;2 ;2 ;4 ;4 ;4 ;4 ;4 ;4 ;5 ;5 ;6 ;1 ];
A_u = unique(A);
z = histcounts(A,[A_u; Inf]);
and you can get the 2-d counts using the histcounts2 command:
x = [1,2,5,6,7,3,4,9,5,2,8]';
y = [1,1,3,6,4,3,6,5,8,7,4]';
x_u = unique(x);
y_u = unique(y);
z2 = histcounts2(x,y,[x_u; Inf],[y_u; Inf])
  3 个评论
dipak sanap
dipak sanap 2016-2-6
Well thanks for the reply. I am aware of these bin counting functions but my task is not to use in built function. Thats why I have to manually create a grid and then count frequency of each bins. Any help regarding nested loop which I have wriiten would be appreciated.
dipak sanap
dipak sanap 2016-2-7
Hey, I got it. I created a 2D meahgrid and counted frequency
in each bin using inpolygon function. here is complete code.
%x = input which I read from my data file.
%y = input which I read from my data file.
N = 401;
mn_x = min(x);
mx_x = max(x);
mn_y = min(y);
mx_y = max(y);
x_rng = linspace(mn_x,mx_x,N);
y_rng = linspace(mx_y,mn_y,N);
[p,q] = meshgrid(x_rng,y_rng);
z = zeros(size(p,1)-1,size(q,2)-1);
for i = 1:size(p,1)-1
for j = 1:size(q,2)-1
xv = [p(i,j),p(i,j+1),p(i,j+1),p(i,j),p(i,j)];
yv = [q(i+1),q(i+1),q(i,j),q(i,j),q(i+1)];
in = inpolygon(x,y,xv,yv);
z(i,j) = numel(x(in));
end
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Histograms 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by