Counts in bins for 2D histogrsm using nested for loop ?
이전 댓글 표시
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
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]);
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
Image Analyst
2016년 2월 6일
편집: Image Analyst
2016년 2월 6일
Cool, I didn't know about histcounts2(). I have the Statistics and Machine Learning Toolbox so I've been using the (in my opinion, poorly named) hist3() to compute 2D histograms.
dipak sanap
2016년 2월 6일
dipak sanap
2016년 2월 7일
카테고리
도움말 센터 및 File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!