Counts in bins for 2D histogrsm using nested for loop ?
1 view (last 30 days)
Show older comments
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
0 Comments
Answers (1)
the cyclist
on 6 Feb 2016
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]);
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 Comments
See Also
Categories
Find more on Histograms in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!