Matlab:加速"find() for each element in ND array"



我有一个ND数组,对于数组中的每个元素,我需要找到它下面向量中最大元素的索引。我已经做了很多次了,所以我真的非常感兴趣的是它尽可能快。

我已经编写了一个函数locate,我用一些有代表性的示例数据调用它。(我使用arrayfun来增加timeit运行函数的次数,以最小化随机波动。(

Xmin = 5;
Xmax = 300;
Xn = 40;
X = linspace(Xmin, Xmax, Xn)';
% iters = 1000;
% timeit(@() arrayfun(@(iter) locate(randi(Xmax + 10, 5, 6, 6), X), 1:iters, 'UniformOutput', false))
timeit(@() locate(randi(Xmax + 10, 5, 6, 6), X))

我的locate原始版本是这样的:

function indices = locate(x, X)
% Preallocate
indices = ones(size(x));
% Find indices
for ix = 1:numel(x)
if x(ix) <= X(1)
indices(ix) = 1;
elseif x(ix) >= X(end)
indices(ix) = length(X) - 1;
else
indices(ix) = find(X <= x(ix), 1, 'last');
end
end
end

我能找到的最快版本是这样的:

function indices = locate(x, X)
% Preallocate
indices = ones(size(x));
% Find indices
% indices(X(1) > x) = 1;  % No need as indices are initialized to 1
for iX = 1:length(X) - 1
indices(X(iX) <= x & X(iX + 1) > x) = iX;
end
indices(X(iX) <= x) = length(X) - 1;
end

你能想出其他更快的方法吗?

您需要的基本上是histc的第二个输出

[pos,bin]=histc(magic(5),X);
bin(bin==0)=1;

最新更新