我有一个包含100K个结构体的数组。下面列出了一个这样的结构体的内容:
迭代:1
块ID:86
块ID的值可以在1到100之间。我想找出每个块ID出现的次数。例如:块ID“1”出现了25次;块ID“98”出现了58次,依此类推。
我在网上查找并尝试了这些链接中提到的选项,但没有得到解决方案: Matlab:计算具有特定内容的结构体数量 如何在Matlab中计算单元格中唯一元素的数量? Matlab:如何计算存储在单元格中的唯一字符串的数量?
我有一个包含100K个结构体的数组。下面列出了一个这样的结构体的内容:
迭代:1
块ID:86
块ID的值可以在1到100之间。我想找出每个块ID出现的次数。例如:块ID“1”出现了25次;块ID“98”出现了58次,依此类推。
我在网上查找并尝试了这些链接中提到的选项,但没有得到解决方案: Matlab:计算具有特定内容的结构体数量 如何在Matlab中计算单元格中唯一元素的数量? Matlab:如何计算存储在单元格中的唯一字符串的数量?
arrayfun
和count_unique
(count_unique不是官方函数 - 它来自matlab中央文件交换,并可在此处找到):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);
为了简单起见,假设有一个大小为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出现次数。
对不起,我的英语很差。
您可以简单地使用Matlab自带的索引技术,结合hist
和unique
函数:
% 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]
这样广泛适用的符号,竟然被如此少数的开发人员所知道(或使用)...[a.member]
,当然只适用于特定的成员类型 ;) - jmetz
arrayfun
的输出是一个数组... - jmetzids
是一个数组吗? - jmetz