登录论坛

查看完整版本 : 在MATLAB中,如何计算与条件关联的索引值的唯一数量?


poster
2019-12-10, 20:48
我有一个二维矩阵,在第一列中包含实验条件的索引,在第二列中包含相应实验的索引,即[condition experiment] 。每行对应一个有趣的事件(一个实验可以产生一个或多个事件)。

计算条件和事件很容易。我想知道如何计算每种给定条件下有多少个独特的实验。

这是我现在使用ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html)的解决方案,但我认为应该有一个更简单或更优雅的解决方案:

idxList = [1 1;... %# There are two experiments for condition 1... 1 2;... 1 2;... 2 1;... %# ...and 1 experiment for condition 2. 2 1]; accumarray(idxList(:,1),idxList(:,2),[],@(x)length(unique(x))) ans = 2 1

回答:

以下是一些替代方案:


使用整个矩阵idxList为subs参数ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html) (即指定用于累积行和列索引),然后求和横跨结果的行非零的数目:

experCounts = sum(accumarray(idxList,1) > 0,2);
首先在idxList上使用UNIQUE (http://www.mathworks.com/help/techdoc/ref/unique.html)删除重复的行,从而简化了对ACCUMARRAY (http://www.mathworks.com/help/techdoc/ref/accumarray.html)的调用:

idxList = unique(idxList,'rows'); experCounts = accumarray(idxList(:,1),1);


更多&回答... (https://stackoverflow.com/questions/4372982)