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
It’s not a particularly smart way to do it, and some of my data vectors m and n are around 100000.
Thanks!
This may look cryptic, but it should give you the same result as your nested loops:
The above assumes
whas been sorted in ascending order.Explanation
Your sorted vector
wcan 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 vectorM. The reason the above code looks so messy (with negations and the function FLIPLR in it) is because you want to find values inxless than or equal to each value inw, but the function HISTC bins data in the following way: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 valueinfis used as an edge value to count everything less than the lowest value inwin the first bin.If you wanted to find values in
xthat are simply less than each value inw, the code would be much simpler: