Comparing elements of one vector with multiple values in a matrix of different size
조회 수: 5 (최근 30일)
이전 댓글 표시
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
dpb
2021년 2월 28일
I wonder if there is any way to build the ranges into something discretize could use...
답변 (1개)
Steven Lord
2021년 2월 28일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!