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