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

5 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

Sean de Wolski
Sean de Wolski el 19 de Mayo de 2011
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

Más respuestas (2)

Andrei Bobrov
Andrei Bobrov el 19 de Mayo de 2011
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 comentario
Ole Gunnar Nordli
Ole Gunnar Nordli el 16 de Nov. de 2020
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

Iniciar sesión para comentar.


Malcolm Campbell
Malcolm Campbell el 12 de Oct. de 2021
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)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by