在MATLAB中有效地循环矢量

亚斯

在Matlab中,我们有以下情形:

v =[1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 .... N N N N];

其中v中的元素始终从1到N递增顺序,并且我们知道N的值。我们要计算v中的'1's'2'...的数量。

当然,我们可以使用如下所示的循环:

for i =  1 : N
    % method A
    tic
    ind = find(v == i)
     ---> do sth with ind 
    t1 = toc;

    % method B
    tic
    ind = v(v == i)
     ---> do sth with ind 
    t2 = toc;

    % method C
    tic
    ind = ismember(v , i)
     ---> do sth with ind 
    t3 = toc;


end

这些方法中的每一个所花费的时间大致等于$ t1 = 0.02秒$,$ t2 = 0.02秒$和$ t3 = 0.03秒$。在我的实际工作中,N很大,整个循环耗时2 -3小时!

您是否有任何想法可以增加执行此过程的时间?任何想法表示赞赏。

迪卡卡

具体情况:排序输入,仅计数

如果您希望获得计数,则此处建议的方法很少。

方法1:

accumarray(v(:),1)

方法2:

diff([0 find([diff(v) 1])])

方法3:

histc(v,1:max(v))

出于性能考虑,我会赌diff,然后accumarray和最后一个histc


一般情况:未排序的输入,计数和索引

对于一般情况,当输入向量v未排序并且您可能还需要与每个相同数字组相对应的索引时,这是将索引存储在单元格数组中的一种方法-

[~,sort_idx] = sort(v);
sorted_v = v(sort_idx);
counts = diff([0 find([diff(sorted_v) 1])])
indices_per_grp = mat2cell(sort_idx,1,counts);

样品运行-

v =
     2     1     3     3     2     4     1     2     1     1     4     3     4   3
counts =
     4     3     4     3
indices_per_grp{1} =
     2     7     9    10
indices_per_grp{2} =
     1     5     8
indices_per_grp{3} =
     3     4    12    14
indices_per_grp{4} =
     6    11    13

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章