フィルターのクリア

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

6 ビュー (過去 30 日間)
Michael
Michael 2011 年 5 月 19 日
回答済み: Malcolm Campbell 2021 年 10 月 12 日
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 Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by