Comparing elements of one vector with multiple values in a matrix of different size
5 views (last 30 days)
Show older comments
Hi,
I have a m x 1 vector and a n x 2 matrix, e.g.,
v = [80; 99; 120; 150; 199; 204; 208; 239; 301; 402; 634; 689];
A = [0,100; 101,200; 201,300; 351,450; 451,550; 575,675; 681,780];
For each row in A, I want to know how many values in v fall between the two values of that row in A. So for the example above, I would like the result to be
output = [2; 3; 3; 1; 0; 1; 1]
Note that that there are gaps between the intervals defined by the rows of A and that there are values of v that don't fall into any of the intervals specified by the rows of A. In other words, sum(output) is not the same as length(v). However, the intervals always have the same size (100), i.e., A(:,2) - A(:,1) is a vector of 100s.
Best I have come up with so far is a for-loop
for i = 1:size(A,1)
output(i) = sum( (A(i,1) <= v) & (v < A(i,2)) );
end
But because my size(A,1) can be as large as 50,000 and I need to do this operation many times, it takes quite long. Is there a better way with indexing?
I was thinking something like
output = sum( (A(:,1) <= v) & (v < A(:,2)) )
but that doesn't work ("Matrix dimensions must agree.")
Any help is appreciated.
Thanks!
5 Comments
dpb
on 28 Feb 2021
I wonder if there is any way to build the ranges into something discretize could use...
Answers (1)
Steven Lord
on 28 Feb 2021
If the rows in A are sorted and disjoint, this does seem like a job for histcounts. Just ignore the bins representing the spaces between the rows in A.
v = [80; 99; 120; 150; 199; 204; 208; 239; 301; 402; 634; 689];
A = [0,100; 101,200; 201,300; 351,450; 451,550; 575,675; 681,780];
edges = reshape(A.', 1, []);
values = histcounts(v, edges)
values(1:2:end)
results = table(A, values(1:2:end).', 'VariableNames', ["BinEdges", "Counts"])
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!