使用非唯一值反向查找

时间:2016-02-11 19:48:03

标签: arrays matlab vectorization reverse-lookup

我想做什么

我有一系列数字:

>> A = [2 2 2 2 1 3 4 4];

我想找到可以找到每个数字的数组索引:

>> B = arrayfun(@(x) {find(A==x)}, 1:4);

换句话说,这个B应该告诉我:

>> for ii=1:4, fprintf('Item %d in location %s\n',ii,num2str(B{ii})); end
Item 1 in location 5
Item 2 in location 1  2  3  4
Item 3 in location 6
Item 4 in location 7  8

它类似于unique的第二个输出参数,但不是第一个(或最后一个)出现,我希望 all 出现。我认为这称为反向查找(其中原始键是数组索引),但如果我错了,请纠正我。

我怎样才能更快地完成?

我上面给出了正确的答案,但它与唯一值的数量非常相称。对于一个真正的问题(其中A有10M个元素,其中包含100k个唯一值),即使这个愚蠢的for循环也要快100倍:

>> B = cell(max(A),1);
>> for ii=1:numel(A), B{A(ii)}(end+1)=ii; end

但我觉得这可能是最好的方法。

我们可以假设A只包含从1到最大的整数(因为如果它没有,我总是可以通过unique传递它来实现它。)

2 个答案:

答案 0 :(得分:3)

这对accumarray来说是一项简单的任务:

out = accumarray(A(:),(1:numel(A)).',[],@(x) {x})  %'

out{1} = 5
out{2} = 3 4 2 1
out{3} = 6
out{4} = 8 7  

但是accumarray因为稳定(在unique的功能意义上)而受到影响,所以你可能想看看{{3}如果这是一个问题。

上述解决方案还假设A填充整数,最好两者之间没有间隙。如果情况并非如此,则无法事先致电unique

A = [2.1 2.1 2.1 2.1 1.1 3.1 4.1 4.1];

[~,~,subs] = unique(A)
out = accumarray(subs(:),(1:numel(A)).',[],@(x) {x})

总而言之,使用浮点数并返回已排序输出的最通用解决方案可能是:

[~,~,subs] = unique(A)
[subs(:,end:-1:1), I] = sortrows(subs(:,end:-1:1));  %// optional
vals = 1:numel(A);                                   
vals = vals(I);                                      %// optional
out = accumarray(subs, vals , [],@(x) {x});

out{1} = 5
out{2} = 1 2 3 4
out{3} = 6
out{4} = 7 8  

基准

function [t] = bench()
    %// data
    a = rand(100);
    b = repmat(a,100);
    A = b(randperm(10000));

    %// functions to compare
    fcns = {
        @() thewaywewalk(A(:).');
        @() cst(A(:).');
    }; 

    % timeit
    t = zeros(2,1);
    for ii = 1:100;
        t = t + cellfun(@timeit, fcns);
    end
    format long
end

function out = thewaywewalk(A) 
    [~,~,subs] = unique(A);
    [subs(:,end:-1:1), I] = sortrows(subs(:,end:-1:1));
    idx = 1:numel(A);
    out = accumarray(subs, idx(I), [],@(x) {x});
end
function out = cst(A) 
    [B, IX] = sort(A);
    out  = mat2cell(IX, 1, diff(find(diff([-Inf,B,Inf])~=0)));
end
0.444075509687511  %// thewaywewalk
0.221888202987325  %// CST-Link

令人惊讶的是,稳定accumarray的版本比不稳定的版本更快,因为Matlab更喜欢使用排序的数组。

答案 1 :(得分:3)

此解决方案应该在O(N * log(N))中进行排序,但是内存密集(需要3倍的输入内存量):

[U, X] = sort(A);
    B  = mat2cell(X, 1, diff(find(diff([Inf,U,-Inf])~=0)));

我对表现感到好奇。

相关问题