Matlab-加快嵌套For循环的速度 [英] Matlab - Speeding up a Nested For Loop

查看:273
本文介绍了Matlab-加快嵌套For循环的速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,但是我对MATLAB不太满意.我有向量x,(n x 1)y,(m x 1)和w = [x;y].我想将M(n + m x 1)定义为M(i)=小于或等于w(i)的x元素数量(对w进行排序).这只是没有削减:

A simple question, but I'm not so great with MATLAB. I have vectors x, (n x 1) y, (m x 1) and w = [x;y]. I want to define M (n+m x 1) as M(i) = number of elements of x that are less than or equal to w(i) (w is sorted). This just isn't cutting it:

N = n + m;
M = zeros(N,1);
for i = 1:N
  for j = 1:n
    if x(j) <= w(i)
      M(i) = M(i) + 1;
    end
  end
end

这不是一个特别聪明的方法,我的一些数据向量m和n大约为100000.

It's not a particularly smart way to do it, and some of my data vectors m and n are around 100000.

谢谢!

推荐答案

这可能看起来很神秘,但它应该为您提供与嵌套循环相同的结果:

This may look cryptic, but it should give you the same result as your nested loops:

M = histc(-x(:)',[-fliplr(w(:)') inf]);
M = cumsum(fliplr(M(1:N)))';

以上假设w已按升序排序.

The above assumes w has been sorted in ascending order.

您排序的向量w可以被认为是bin边缘,可用于通过 FLIPLR )是因为您要在x 中查找小于或等于的值,但要在w中查找每个值,但是要使用功能

Your sorted vector w can be thought of as bin edges to use in creating a histogram with the HISTC function. Once you count the number of values that fall in each bin (i.e. between the edges), a cumulative sum over those bins using the CUMSUM function will give you your vector M. The reason the above code looks so messy (with negations and the function FLIPLR in it) is because you want to find values in x less than or equal to each value in w, but the function HISTC bins data in the following way:

n(k)如果edges(k) <= x(i) < edges(k+1)则对值x(i)进行计数.

n(k) counts the value x(i) if edges(k) <= x(i) < edges(k+1).

请注意,小于 用于每个bin的上限.您可能希望翻转行为,以便根据规则edges(k) < x(i) <= edges(k+1)进行合并,这可以通过对要合并的值取反,对边取反,对边取反来实现(因为将边输入为 inf 用作边值,以计算小于第一个bin中w的最小值的所有内容.

Notice that less than is used for the upper limit of each bin. You would want to flip the behavior so that you bin according to the rule edges(k) < x(i) <= edges(k+1), which can be achieved by negating the values to be binned, negating the edges, flipping the edges (since the edge input to HISTC must be monotonically nondecreasing), and then flipping the bin counts returned. The value inf is used as an edge value to count everything less than the lowest value in w in the first bin.

如果您想在x中查找比w中的每个值简单 个值的代码,则代码会简单得多:

If you wanted to find values in x that are simply less than each value in w, the code would be much simpler:

M = histc(x(:)',[-inf w(:)']);
M = cumsum(M(1:N))';

这篇关于Matlab-加快嵌套For循环的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆