Clear Filters
Clear Filters

How do I group a sample data by a column into small groups?

1 view (last 30 days)
I have a sample dataset of the form below and I want to sort into group of A = 11 - 20, B = 21 - 30, C = 31 - 40, etc. using the second column to do the sorting. I tried this
N = sortrows(N,2);
if N(:,2)<=0;
N0 = N;
elseif (N(:,2)>=1) & (N(:,2)<=10);
N10 = N;
elseif (N(:,2)>10) & (N(:,2)<=20);
N20 = N;
elseif (N(:,2)>20) & (N(:,2)<=30);
N30 = N;
elseif (N(:,2)>30) & (N(:,2)<=40);
N40 = N;
if N(:,2) > 40
N50 = N50(N);
end
but nothing was displayed
DATASET
16.07 88.9 1007
15.91 89.1 1007
19.87 67.48 1008
20.45 61.71 1008
21.62 53.97 1009
22.02 47.95 1009
18.54 82.9 1006
18.66 82 1006
18.46 84.1 1006
18.36 83.6 1006
24.38 54.33 1008
25.18 50.33 1008
25.9 46.73 1008
26.46 45.79 1008
30.29 31.58 1006
30.33 29.83 1006
31.76 24.36 1004
32.37 24.63 1004
32.38 26.74 1004
32.23 24.22 1004

Accepted Answer

dpb
dpb on 10 Jun 2015
>> edges=[-inf 1 10:10:40 inf]; % set up bin edges
>> [n,bin]=histc(dat(:,2),edges) % count, bin...
>> for i=unique(bin).',dat(bin==i,2),end % display results
ans =
29.8300
24.3600
24.6300
26.7400
24.2200
ans =
31.5800
ans =
88.9000
89.1000
67.4800
61.7100
53.9700
47.9500
82.9000
82.0000
84.1000
83.6000
54.3300
50.3300
46.7300
45.7900
  7 Comments
dpb
dpb on 11 Jun 2015
Edited: dpb on 11 Jun 2015
As I said, put what you want inside the loop...
"...each ans ought to be A, B, C,..."
Do NOT do this...for reasons and alternatives see the FAQ How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop?
j=0; % initialize counter for cell array
for i=unique(bin).'
j=j+1; % increment counter
a{j}=dat(bin==i,:); % store this set
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!