determining whether a number lies in any of the intervals of a 2 column matrix
3 次查看(过去 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       3
5       10
15      18
20      22
29      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!
0 个评论
采纳的回答
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
0 个评论
更多回答(2 个)
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
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
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)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!