texnic
texnic

Reputation: 4098

Find vector elements matching two conditions in Matlab

I have a vector a = [1 5 3 4 2]. I'd like to find all elements of a, which are 1<a<5. How do I do it in Matlab?

Personally I've developed one solution, but it's cumbersome:

a = [1 5 3 4 2];
ix = find(a>1);
ix = ix(find(a(ix)<5));
disp(a(ix))

What's a better way?

Upvotes: 7

Views: 34997

Answers (3)

Shrein
Shrein

Reputation: 291

A simple tweak to your code would simplify it:

a = [1 5 3 4 2];
disp(find(a>1&a<5))

Upvotes: 5

leonidas1573
leonidas1573

Reputation: 31

ismember is a good choice for discrete cases

a = [1 5 3 4 2];
find(ismember(a, 2:4))

Upvotes: 3

Dang Khoa
Dang Khoa

Reputation: 5823

Use logical indexing:

>> a = [1 5 3 4 2];
>> a = a(1 < a & a < 5)
a = 
    3    4    2

Upvotes: 14

Related Questions