David Guo
David Guo

Reputation: 1759

how to count the row which match a combined condition?

For example, I have matrix m =

1 0 1 0 1 1;
0 1 0 1 0 1;
1 0 1 0 1 1;
0 1 0 1 0 1

I want count the number of row which first element m(i, 1) = 1 and third element m(i,3) = 1.

Use for loop will work. But, I hope there a easy way to do that. octave function sum SEEMS just support one condition.

Upvotes: 0

Views: 301

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51480

It's pretty easy to find rows matching a certain condition in octave:

m(:,1) == 1 # m(i, 1) = 1
m(:,3) == 1 # m(i, 3) = 1

You could combine multiple conditions using octave & (logical and) and | (logical or) operators:

(m(:,1) == 1) & (m(:,3) == 1)

If you only want a number of matching roes, you could use a sum function:

sum((m(:,1) == 1) & (m(:,3) == 1))

Upvotes: 1

Related Questions