# How to find elements of a vector falling between minimum and maximum of an other vector without loop.

1 vue (au cours des 30 derniers jours)
Levente Gellért le 4 Juil 2021
Dear Community,
is there other way, than a loop to find elements in a vector b falling between the minimum and the maximum of vector a?
Let's say:
a=(1:1:10);
b=[5.5 11];
for i=1:length(b)
if b(:,i)>min(a) && b(:,i)<max(a)
c(:,i)=1;
else
c(:,i)=0;
end
end
##### 0 commentairesAfficher -2 commentaires plus anciensMasquer -2 commentaires plus anciens

Connectez-vous pour commenter.

### Réponse acceptée

Sulaymon Eshkabilov le 4 Juil 2021
Logical indexing is the best option, e.g.:
a=(1:1:10);
b=[5.5 11; 13, 3; 10.5 10];
IDX = find(b>min(a) & b<max(a));
C(IDX)=1;
##### 2 commentairesAfficher AucuneMasquer Aucune
Stephen23 le 5 Juil 2021
Modifié(e) : Stephen23 le 5 Juil 2021
This answer actually shows linear indexing (the output from the superfluous FIND), not logical indexing.
Remove the superfluous FIND to use simpler and more efficient logical indexing.
Also note that because C is not preallocated, it could have fewer elements than a.
Levente Gellért le 6 Juil 2021
Dear All, many thanks for the nice comments! lg

Connectez-vous pour commenter.

### Plus de réponses (3)

Yazan le 4 Juil 2021
c = zeros(size(b));
c(b>min(a(:)) & b<max(a(:))) = 1;
##### 2 commentairesAfficher AucuneMasquer Aucune
Stephen23 le 5 Juil 2021
Simpler:
c = b>min(a(:)) & b<max(a(:))
Levente Gellért le 6 Juil 2021
Dear All, many thanks for the nice comments! lg

Connectez-vous pour commenter.

dpb le 4 Juil 2021
>> iswithin(b,min(a),max(a))
ans =
1×2 logical array
1 0
>>
is a common-enough idiom I have a utility function for the purpose--
>> function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
end
It isn't any different than writing the logical expression in line except as a function it has the advantage of moving the test to a lower level that is often very helpful in writing concise, legible expressions at the user level.
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Levente Gellért le 6 Juil 2021
Dear All, many thanks for the nice comments! lg

Connectez-vous pour commenter.

Matt J le 5 Juil 2021
a=(1:1:10);
b=[5.5 11];
[~,~,c]=histcounts([0,5.5,10,11],[min(a),max(a)+eps(max(a))])
c = 1×4
0 1 1 0
##### 1 commentaireAfficher -1 commentaires plus anciensMasquer -1 commentaires plus anciens
Levente Gellért le 6 Juil 2021
Dear All, many thanks for the nice comments! lg

Connectez-vous pour commenter.

### Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by