在matlab中查找struct数组中的出现次数

时间:2012-08-02 20:33:38

标签: matlab

我有一个100K结构的数组。我在下面列出了一个这样的结构的内容:

迭代:1

BLOCKID:86

BlockID的值可以是1到100.我想找出BlockID的出现次数。例如:BlockID" 1"发生了25次; BlockID" 98"发生了58次,等等。

我在线查看并尝试了这些链接中提到的选项,但无法获得解决方案: Matlab: Count number of structs that have a specific content how to count unique elements of a cell in matlab? Matlab: How to calculate how many unique strings are stored in the cell?

3 个答案:

答案 0 :(得分:1)

您可以使用arrayfuncount_unique(count_unique不是官方函数 - 它来自matlab中央文件交换,可以找到here):

ids= arrayfun(@(x)x.BlockID, struct1);
[vals, counts] = count_unique(ids);

NB:正如rody_o所指出的那样(尽管他/她错过了索引是不必要的这一事实),还有另一种方法来连接,ids,即

ids = [struct1.BlockID];

或者,如果您愿意,可以创建自己的count_unique功能,

function [counts, uns] = count_unique(ids)
uns= unique(ids);
counts = arrayfun(@(x)sum(ids == x), uns);

答案 1 :(得分:1)

为简单起见,假设有一个大小为10的结构数组,其BlockID值介于'1'和'3'之间:

%generate the struct array
for n = 1:10 
    structs(n).BlockID = num2str(randi(3));
end
%structs.BlockID : 3     2     1     3     3     2     1     1     2     2

要找出BlockID的出现次数:

count = accumarray(str2double({structs.BlockID})',1);
%count : 3     4     3

现在count(i)是值'i'的BlockID的出现次数。

抱歉我的英语不好。

答案 2 :(得分:1)

您可以简单地使用Matlab自己的索引技术,结合histunique

% sample data

a(1).BlockID   = 68
a(1).iteration = 1

a(2).BlockID   = 88
a(2).iteration = 12

a(3).BlockID   = 88
a(3).iteration = 14

a(4).BlockID   = 16
a(4).iteration = 18

% collect all BlockID values into array
b = [a.BlockID];

% count unique entries
[occurrences, entries] = hist(b, unique(b))

输出:

occurrences =
    1     1     2
entries =
    16    68    88

我总是觉得令人惊讶的是,很少有开发人员知道(或使用)[struct(indices).member]符号广泛适用的东西......