Automatically adjust bin width
3 views (last 30 days)
Show older comments
Dear all,
I would like to do the following:
- Bin TM_3 using bin width of 2 and select the coincident R_3.
- The binned R_3 should have >= 150 data points for each bin.
- 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 Comments
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 Comments
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)
edges(1:2)
y = x(edges(1) <= x & x < edges(2))
Note that y has counts(1) elements.
See Also
Categories
Find more on Data Distribution Plots 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!