BillyJean
BillyJean

Reputation: 1577

selecting subset of matrix based on condition

I have the following matrix

test = [1 2 3 4;
        2 3 4 5;
        3 4 5 6;
        4 5 6 7;
        5 6 7 8];

I would like to select the rows whose first entry has a value between 1 and 3. I tried with

test(test(:,1)<3 && test(:,1)>1)

but that gave me an error. Then I tried with

test(1<test(:,1)<3)

but that doesn't give me the desired result 2 3 4 5. Is there a way to obtain this is Matlab?

Upvotes: 1

Views: 562

Answers (2)

mabe
mabe

Reputation: 135

In order to logically compare vectors one by one you have to use & instead of &&:

test(test(:,1)<3 & test(:,1)>1,:)

This produces the answer:

 2     3     4     5

Upvotes: 1

Jo&#227;o Almeida
Jo&#227;o Almeida

Reputation: 5067

Try this, I couldn't test it in Matlab but it should work.

test((1 < test(:,1) && test(:,1) < 3),:)

Explanation:

This (1 < test(:,1) && test(:,1) < 3) Get's a binary array with the rows that fit the criteria, then you use that to select the rows.

See here for more information.

Upvotes: 2

Related Questions