필터 지우기
필터 지우기

determining whether a number lies in any of the intervals of a 2 column matrix

조회 수: 6 (최근 30일)
basically i have a matrix of numbers, single column, such as the following:
A = [2; 4; 17; 23; 30]
and i have another matrix with 2 columns, which represents an interval:
B =
1 &nbsp&nbsp&nbsp&nbsp&nbsp 3
5 &nbsp&nbsp&nbsp&nbsp&nbsp 10
15 &nbsp&nbsp&nbsp&nbsp 18
20 &nbsp&nbsp&nbsp&nbsp 22
29 &nbsp&nbsp&nbsp&nbsp 33
What I am tryin to do is have MATLAB go through each of the numbers in matrix A and have them run through each interval in matrix B to check whether or not it lies in any of those intervals.
For example,
A(1) = 2
This lies between 1 and 3 (the first interval in the list B, so that case would be a true.
The second case of A(2) = 4 does not lie in any of the intervals (1 to 3, nor 5 to 10, nor any of the ones below those two), so this would be a false for that value. I really am not sure how to do this.. I tried setting up a 'for' loop and got confused very quickly. Any help at all would be SO appreciated. thanks in advance!

채택된 답변

Sean de Wolski
Sean de Wolski 2011년 5월 19일
I have an elementary for-loop running twice as fast as the arrayfun method.
idx = false(size(A));
for ii = 1:length(A)
idx(ii) = any((A(ii)>B(:,1))&(A(ii)<B(:,2)));
end

추가 답변 (2개)

Andrei Bobrov
Andrei Bobrov 2011년 5월 19일
K = min(B(:)):max(B(:));
idx = arrayfun(@(x)find(K>=B(x,1) & K<=B(x,2)),1:length(A),'un',0);
out = A(ismember(A,K([idx{:}])));
  댓글 수: 1
Ole Gunnar Nordli
Ole Gunnar Nordli 2020년 11월 16일
I am trying to find a interval where one number lies within in a 1.000 simulations.
Can I place the value I am looking for as A within the interval B? I do get errors, how do I fix this?
Thanks

댓글을 달려면 로그인하십시오.


Malcolm Campbell
Malcolm Campbell 2021년 10월 12일
What about:
bin_edges = sort(reshape(B,numel(B),1));
[~,~,bin] = histcounts(A,bin_edges);
idx = ~isEven(bin);
Works fast for me! (Much faster than the for loop in the accepted answer)

카테고리

Help CenterFile Exchange에서 Numeric Types에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by