如何在Matlab中加速对分位数的调用?

Chr*_*lor 8 optimization matlab vectorization bsxfun

我有一个MATLAB例程,有一个相当明显的瓶颈.我已经分析了这个函数,结果是在函数中使用了2/3的计算时间levels:

在此输入图像描述

该函数levels采用浮点矩阵并将每列拆分为nLevels桶,返回与输入大小相同的矩阵,每个条目替换为它所属的桶的数量.

为此,我使用该quantile函数获取存储区限制,并使用循环将条目分配给存储区.这是我的实现:

function [Y q] = levels(X,nLevels)
% "Assign each of the elements of X to an integer-valued level"

p = linspace(0, 1.0, nLevels+1);

q = quantile(X,p);
if isvector(q)
    q=transpose(q);
end

Y = zeros(size(X));

for i = 1:nLevels
    % "The variables g and l indicate the entries that are respectively greater than
    % or less than the relevant bucket limits. The line Y(g & l) = i is assigning the
    % value i to any element that falls in this bucket."
    if i ~= nLevels % "The default; doesnt include upper bound"
        g = bsxfun(@ge,X,q(i,:));
        l = bsxfun(@lt,X,q(i+1,:));
    else            % "For the final level we include the upper bound"
        g = bsxfun(@ge,X,q(i,:));
        l = bsxfun(@le,X,q(i+1,:));
    end
    Y(g & l) = i;
end
Run Code Online (Sandbox Code Playgroud)

有什么办法可以加快速度吗?代码可以矢量化吗?

And*_*ein 4

如果我理解正确的话,你想知道每个桶里掉了多少物品。使用:

n = hist(Y,nbins)

尽管我不确定这是否有助于加速。这样就更干净了。

编辑:根据评论:

您可以使用histc的第二个输出参数

[n,bin] = histc(...) 还返回索引矩阵 bin。如果 x 是向量,则 n(k) = >sum(bin==k)。对于超出范围的值,bin 为零。如果 x 是 M×N 矩阵,则