使用MATLAB计算两个向量

时间:2015-01-20 17:47:36

标签: matlab

我尝试编译下面的代码,但它不起作用。基本上,我想计算a中小于或等于x中每个元素的元素数。请帮忙。

a = exprnd(1,10000, 1);
x = 0:0.02:10;
for i = 1:length(x);
    count = 0;
    for j = 1:length(a);
        if (a(j) <= x(i))
          count = count + 1;
        end
    end
end

3 个答案:

答案 0 :(得分:5)

在您的情况下,bsxfun()可以让事情变得更轻松。

你可以试试这个:

result = sum(bsxfun(@le, a(:), x(:).'));

答案 1 :(得分:2)

让您的方法有效:

首先我们修复您的原始方法:

a = exprnd(1,10000, 1);
x = 0:0.02:10;
count = zeros(size(x)); %%// <= Preallocate the count-vector
for i = 1:length(x);
    %%// <= removed the line "count = 0"
    for j = 1:length(a);
        if (a(j) <= x(i))
          count(i) = count(i) + 1; %%// <= Changed count to count(i)
        end
    end
end

这将使您的方法有效。如果您想为相对较大的向量ax计算此值,则这将非常慢,因为整体复杂度为O(n^2)。 (假设n==length(x)==length(a)。)

您可以使用不同的方法来加快运行时间:

使用O(n*log(n))

的复杂性方法sort

以下是复杂度O(n*log(n))而非O(n^2)的算法。 它基于Matlab的sort稳定并且返回的位置。假设x已排序,如果您对[a(:); x(:)]进行排序,则x(1)的新位置将为1加上小于或等于a的元素数量到x(1)x(2)的新职位将为2加上a小于或等于x(2)的元素数量。因此,a中小于x(i)的元素数量等于x(i)减去i的新位置。

function aSmallerThanxMat = aSmallerThanx(a, x)
%%// Remember dimension of x
dimX = size(x);
%%// Sort x and remember original ordering Ix
[xsorted, Ix] = sort(x(:));
%%// How many as are smaller than sortedX
[~,Iaxsorted] = sort([a(:); xsorted(:)]);
Iaxsortedinv(Iaxsorted) = 1:numel(Iaxsorted);
aSmallerThanSortedx = Iaxsortedinv(numel(a)+1:end)-(1:numel(xsorted));
%%// Get original ordering of x back
aSmallerThanx(Ix) = aSmallerThanSortedx;
%%// Reshape x to original array size 
aSmallerThanxMat = reshape(aSmallerThanx, dimX);

这种方法可能有点难以掌握,但对于大型向量,您将获得相当大的加速。

使用sortfor

的类似方法

这种方法的概念非常相似,但更传统的使用循环: 首先,我们对xa进行排序。然后我们逐步完成x(i_x)。如果x(i_x)大于当前a(i_a),我们会增加i_a。如果它小于当前i_a,则i_a-1a中小于或等于x(i_x)的元素数。

function aSmallerThanx = aSmallerThanx(a, x)
asorted = sort(a(:));
[xsorted, Ix] = sort(x(:));
aSmallerThanx = zeros(size(x));

i_a = 1;
for i_x = 1:numel(xsorted)
    for i_a = i_a:numel(asorted)+1
        if i_a>numel(asorted) || xsorted(i_x)<asorted(i_a)
            aSmallerThanx(Ix(i_x)) = i_a-1;
            break
        end
    end
end

使用histc的方法:

这个更好:它会在x的值之间创建容器,计算落入每个容器的a的值,然后从左边开始对它们求和。

function result = aSmallerThanx(a, x)
[xsorted, Ix] = sort(x(:));
bincounts = histc(a, [-Inf; xsorted]);
result(Ix) = cumsum(bincounts(1:end-1));

比较

以下是您的方法的运行时比较, Ander Biguri for+sum循环方法, mehmet bsxfun方法,两者使用sorthistc方法的方法: 对于长度为16384的向量,histc方法比原始方法快2300倍。   Runtime Comparison

答案 2 :(得分:0)

使用矢量化的简单方法:

 count=zeros(length(x),1);  
 for ii=1:length(x)
       count(ii)=count(ii)+sum(a<=x(ii));
 end