performancematlabfindaccelerate

Matlab: Speed up "find() for each element in ND array"


I have an ND array and, for each element in the array, I need to find the index of the largest element in a vector that is below it. I'm doing this maaaany times so I really super extra interested in it being as fast as possible.

I have written a function locate that I call with some representative example data. (I use arrayfun to increase the number of times timeit runs the function to minimize random fluctuations.)

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))

My original version of locate looked like this:

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

And the fastest version that I can muster looks like this:

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

Can you think of any other way that would be faster?


Solution

  • what you need is basically the 2nd output of histc

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