# Automatically adjust bin width

5 views (last 30 days)
Eli on 8 Dec 2023
Commented: Steven Lord on 9 Dec 2023
Dear all,
I would like to do the following:
1. Bin TM_3 using bin width of 2 and select the coincident R_3.
2. The binned R_3 should have >= 150 data points for each bin.
3. If < 150, the bin width is extended until 150 data points is obtained.
I am having problems with extending until 150 data points are obtained. I have attached my code below. If there are other better methods, please let me know. Thank you very much for your time.
clear; clc;
load('Test_CC.mat');
TP = [TM_3 R_3];
TP_s = sortrows(TP); % Sort ascending based on Tm
bin_a1 = (TP_s(1:end-2,1));
bin_b1 = (TP_s(1:end-2,1)+2);
% % Initial binning according to specified width ==========================
for i = 1:length(TP_s)
for j = 1:length(bin_b1)
bin_c1 = find(TP_s(:,1)>= bin_a1(i) & TP_s(:,1) <= bin_b1(i)); % Initial bin of TM_3
bin_d1 = length(bin_c1); % Length of initial bin
if bin_d1 < 150 % Check if binned data < 150
bin_c2 = find(TP_s(:,1)>= bin_a1(i) & TP_s(:,1) <= bin_b1(j)); % Try different end bin until 150
if length(bin_c2) == 150 % Check if new binned data >= 150
bin_b1(i,:) = bin_b1(j); % New end bin
break; % If >=150, break.
end
end
end
bin_c3{i,:} = bin_c2;
bin_a1(i+1,:) = bin_b1(i)-1;
bin_b1(i+1,:) = bin_a1(i+1)+2;
end
bin_a2 = bin_a1(find(bin_b1 < max(T_mx)));
bin_b2 = bin_b1(find(bin_b1 < max(T_mx)));
for i = 1:length(bin_a2)
bin_e1{i,:} = TP_s(find(TP_s(:,1)>= bin_a2(i) & TP_s(:,1) <= bin_b2(i)),2); % Bin of R_3
end
##### 0 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Answers (1)

Steven Lord on 8 Dec 2023
Rather than trying to implement the binning operation yourself, I recommend you call the histcounts function in a looping construct like while. Each call to histcounts in each loop iteration would use a different value for the BinWidth name-value argument until the results satisfy your requirements.
##### 3 CommentsShow 1 older commentHide 1 older comment
Stephen23 on 9 Dec 2023
"As far as I am aware, we are unable to fix the bin width to 2 using histcounts. "
Steven Lord on 9 Dec 2023
Make some sample data.
x = randn(1, 1e4);
Call the function.
[counts, edges] = histcounts(x, 'BinWidth', 2);
Check.
counts(1)
ans = 226
edges(1:2)
ans = 1×2
-4 -2
y = x(edges(1) <= x & x < edges(2))
y = 1×226
-2.0622 -2.9162 -2.1681 -2.3395 -2.3836 -2.3846 -2.5135 -2.2379 -2.2485 -2.5731 -2.6816 -2.1627 -2.8525 -2.1318 -2.1354 -2.0405 -2.3477 -2.2229 -2.0310 -2.3010 -2.5034 -2.5427 -2.4107 -2.4162 -2.0997 -2.5881 -2.1372 -2.1654 -2.7541 -2.6939
Note that y has counts(1) elements.

Sign in to comment.

### Categories

Find more on Data Distribution Plots in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!