我有一个矩阵,每个人的家庭id在第一列,他们的年龄在第二列:
1 32
1 36
1 8
2 50
2 55
3 45
3 40
3 4
3 5
4 23
我想要做的是找出具有特定家庭id的特定年龄组之间的人数。下面是一些年龄类的示例:
0
1-2
3
4-6
7-10
etc
所以如果我搜索家庭id 1
,我想找到7-10类的1
,当我搜索家庭id 3
时,我想找到4-6类的2
。我该怎么做呢?
发布于 2017-08-10 20:07:02
histcounts
计算直方图,您可以将edges
输入到直方图中(边缘是每个bin的界限);
完整的例子说明了如何在2行代码中使用你的数据和随机范围来做这件事。你需要知道的唯一一件事是,当你想要一个单独的数字作为bin时,你只需将bin的边缘添加到非常接近值本身的位置。在您的例子中,它们是整数,所以-0.1 +0.1就足够了。
M=[1 32
1 36
1 8
2 50
2 55
3 45
3 40
3 4
3 5
4 23];
ranges=[-0.1 0.1 1 4 20 30 40]; % random
% separate the matrix into cells with unique IDs
Mcell = arrayfun(@(x) M(M(:,1) == x, :), unique(M(:,1)), 'uniformoutput', false);
% Count bins in each cell
result=cellfun(@(x)(histcounts(x(:,2),ranges)),Mcell,'uniformoutput',false)
发布于 2017-08-10 20:23:43
你要找的肯定是直方图。但是,我在MATLAB中找不到一个内置函数来支持您的问题中的零宽度存储箱。因此,我编写了一个关于如何手动计算所需直方图的小脚本:
% the age data
% (first column: id
% second column: age)
mat_data = [1 32
1 36
1 8
2 50
2 55
3 45
3 40
3 4
3 5
4 23];
% the age classes
% (one class per row,
% lower bound in first column,
% upper bound in second column)
age_classes = [0, 0; ...
1, 2; ...
3, 3; ...
4, 6; ...
7, 10];
% determine all ids
ids = unique(mat_data(:, 1));
% initialize the output matrix
mat_counts = zeros(size(age_classes, 1), length(ids));
% count the number of entries for each id and age class
for idx_id = 1 : length(ids)
cur_data = mat_data(mat_data(:, 1) == ids(idx_id), 2);
for idx_age_class = 1 : length(age_classes)
cur_age_class = age_classes(idx_age_class, :);
mat_counts(idx_age_class, idx_id) = length(find(cur_data >= cur_age_class(1) & cur_data <= cur_age_class(2)));
end
end
% plot everything
% create the x-axis labels
xticks = {};
for idx_age_class = 1 : length(age_classes)
if length(unique(age_classes(idx_age_class, :))) == 1
xticks{idx_age_class} = num2str(age_classes(idx_age_class, 1));
else
xticks{idx_age_class} = sprintf('%.0f-%.0f', age_classes(idx_age_class, 1), age_classes(idx_age_class, 2));
end
end
figure(1);
bar(mat_counts);
set(gca, 'xticklabel', xticks);
legend(cellfun(@num2str, num2cell(ids)))
xlabel('age class')
ylabel('count')
这解决了你的问题吗?
https://stackoverflow.com/questions/45612923
复制相似问题