Sunday 22 April 2012

[FIND] function in MATLAB

Matlab is really a good tool to implement some brainstorm idea in quick way, however, for loop is not efficient especially for large database search problem. FIND built-in function can solve the problem very well. Now I understand why the runtime of compilation-based code is much more efficient than interpretation-based program.

For example, the first program is several orders of magnitude faster than the second one.

% The codes with find

for i = 1:NumQuadrats
    tic
    ind = find(x >= xmin + (i - 1)*step & x < xmin + i*step);
    quadrat{i} = [x(ind) y(ind) z(ind)];
    x(ind) = [];
    y(ind) = [];
    z(ind) = [];
    fprintf('Quadrat %d has been done !\n', i);
    toc
end

% The codes without find

for i = 1:NumQuadrats
    index = [];
    tic
    for j = 1:size(x,1)
        if x(j) >= xmin + (i - 1)*step && x(j) < xmin + i*step
            quadrat{i} = [quadrat{i};[x(j) y(j) z(j)]];
            index = [index;j];
        end
    end
    x(index) = [];
    y(index) = [];
    z(index) = [];
    fprintf('Quadrat %d has been done !\n', i);
    toc
end


No comments:

Post a Comment