2012-08-02 82 views
3

我有一个100K结构的数组。我列出这样一个结构的内容如下:在matlab中查找结构数组中出现的次数

迭代:1

块标识:86

块标识可在1到100.我想找出块标识的出现次数之间的值。例如: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?

回答

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); 
+0

谢谢,这工作。我正在使用arrayfun,但无法继续获取唯一值。我为你提到的增加了一个额外的步骤。使用cell2mat将“id”转换为矩阵,其余部分是相同的。再次感谢。 – Sarvavyapi 2012-08-02 21:24:36

+0

@Sarvavyapi:太好了,我很高兴这解决了你的问题! – jmetz 2012-08-02 21:31:08

+0

@Sarvavyapi:你能再解释一下为什么你需要cell2mat吗? 'arrayfun'的输出是一个数组... – jmetz 2012-08-02 21:33:15

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 

要找出块标识的出现次数:

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

现在算(i)是有价值的“我”块标识的出现次数。

对不起,我英文很差。

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]符号被少数开发人员知道(或使用)...

+0

提示:连接时不需要索引 - 你提到的符号更简单:'[a.member]'当然只有通用的特定成员类型;) – jmetz 2012-08-03 17:45:15

+0

真的,我忘了它是一种习惯我的一贯写结构你*做*需要索引... – 2012-08-03 21:59:12

+0

感谢大家的回应。我会尝试这些选项并在此处给出结果。 – Sarvavyapi 2012-08-06 19:41:27