matlab中的histc,Matlab histc与矢量箱

如果我有两个矩阵A和B,大小为[m×n]和[p×n],并且我想要找出B中每行出现在A中的次数,例如:

>> A = rand(5,3)

A =

0.1419 0.6557 0.7577

0.4218 0.0357 0.7431

0.9157 0.8491 0.3922

0.7922 0.9340 0.6555

0.9595 0.6787 0.1712

>> B = [A(2,:); A(1,:); A(2,:); A(3,:); A(3,:); A(4,:); A(5,:)]

B =

0.4218 0.0357 0.7431

0.1419 0.6557 0.7577

0.4218 0.0357 0.7431

0.9157 0.8491 0.3922

0.9157 0.8491 0.3922

0.7922 0.9340 0.6555

0.9595 0.6787 0.1712在这种情况下的答案是

ans =

1 2 2 1 1尽管不像这个例子,一般情况下m >> p

如果A和B是向量,则matlab的histc可以完成这项工作,但如果分箱是向量,似乎并不等同。

目前我是这样做的:

for i=1:length(B)

indices(i) = find(abs(A/B(i,:)-1) < 1e-15);

% division requires a tolerance due to numerical issues

end

histc(indices, 1:size(A,1))

ans =

1 2 2 1 1但是因为我有很多这样的矩阵B,而且A和B都很大,所以这是非常慢的。任何想法如何改善呢?

编辑:

看看迄今为止的方法,我有以下数据:

A 7871139x3 188907336 double

B 902x3 21648 double为了让事情更快,我只打算使用B的前10行

B = B(1:10,:);请注意,对于完整的应用程序,我(当前)有> 10 ^ 4个这样的矩阵(这最终会> 10 ^ 6 ....)

我的第一个方法:

tic, C = get_vector_index(A,B); toc

Elapsed time is 36.630107 seconds.bdecaf的方法(可以通过删除if语句并使用L1距离代替L2距离将其减少到约25秒)

>> tic, C1 = get_vector_index(A,B); toc

Elapsed time is 28.957243 seconds.

>> isequal(C, C1)

ans =

1oli的pdist2方法

>> tic, C2 = get_vector_index(A,B); toc

Elapsed time is 7.244965 seconds.

>> isequal(C,C2)

ans =

1奥利的标准化方法

>> tic, C3 = get_vector_index(A,B); toc

Elapsed time is 3.756682 seconds.

>> isequal(C,C3)

ans =

1最后,我想出了另一种方法,我搜索第一列,然后搜索第一列内的第二列,递归直到列被耗尽。这是迄今为止最快的....

N = size(A,2);

loc = zeros(size(B,1),1);

for i=1:size(B,1)

idx{1} = find(A(:,1)==B(i,1));

for k=2:N,

idx{k} = idx{k-1}(find(A(idx{k-1},k)==B(i,k)));

end

loc(i) = idx{end};

end

C = histc(loc, 1:size(A,1));这导致:

>> tic, C4 = get_vector_index(A,B); toc

Elapsed time is 1.314370 seconds.

>> isequal(C, C4)

ans =

1另请注意,使用intersect要慢得多:

>> tic, [~,IA] = intersect(A,B,'rows'); C5 = histc(IA,1:size(A,1)); toc

Elapsed time is 44.392593 seconds.

>> isequal(C,C5)

ans =

1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值