首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在矩阵中查找条件值

在矩阵中查找条件值
EN

Stack Overflow用户
提问于 2017-08-10 19:48:56
回答 2查看 68关注 0票数 0

我有一个矩阵,每个人的家庭id在第一列,他们的年龄在第二列:

代码语言:javascript
运行
复制
1  32
1  36
1  8
2  50
2  55
3  45
3  40
3  4
3  5
4  23

我想要做的是找出具有特定家庭id的特定年龄组之间的人数。下面是一些年龄类的示例:

代码语言:javascript
运行
复制
0
1-2
3
4-6 
7-10
etc

所以如果我搜索家庭id 1,我想找到7-10类的1,当我搜索家庭id 3时,我想找到4-6类的2。我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-10 20:07:02

histcounts计算直方图,您可以将edges输入到直方图中(边缘是每个bin的界限);

完整的例子说明了如何在2行代码中使用你的数据和随机范围来做这件事。你需要知道的唯一一件事是,当你想要一个单独的数字作为bin时,你只需将bin的边缘添加到非常接近值本身的位置。在您的例子中,它们是整数,所以-0.1 +0.1就足够了。

代码语言:javascript
运行
复制
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)
票数 1
EN

Stack Overflow用户

发布于 2017-08-10 20:23:43

你要找的肯定是直方图。但是,我在MATLAB中找不到一个内置函数来支持您的问题中的零宽度存储箱。因此,我编写了一个关于如何手动计算所需直方图的小脚本:

代码语言:javascript
运行
复制
% 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')

这解决了你的问题吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45612923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档