在矩阵矩阵中查找条件值

  • 本文关键字:条件 查找 matlab matrix
  • 更新时间 :
  • 英文 :


我有一个矩阵,第一列中有家庭身份证,第二列有年龄:

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

因此,如果我搜索家庭身份证1我想在 7-10 类中找到1,在寻找家庭身份证3我想在 4-6 类中找到2。我该怎么做?

histcounts

计算直方图,您可以输入edges(边缘是每个箱的限制(;

有关如何使用您的数据和随机范围在 2 行中执行此操作的完整示例。您唯一需要知道的是,每当您想要单个数字作为箱时,您只需将箱的边缘非常非常接近值本身添加即可。在您的情况下,它们是整数,因此 -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)

您正在寻找的肯定是直方图。但是,我在 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')

这能解决你的问题吗?

最新更新