Febri Dwi Laksono
Febri Dwi Laksono

Reputation: 309

How to count how many number of value 1 in spesific row

I have matrix :

 A=[ 1 2 3 4 5 0 0 0 0 0 0;
     0 1 2 3 4 5 0 0 0 0 0;
     0 0 0 1 2 3 4 5 0 0 0;
     0 0 1 2 3 4 5 0 0 0 0;
     0 0 0 0 0 1 2 3 4 5 0;
     1 2 3 4 5 0 0 0 0 0 0]

I want to search for the number 1 in my matrix from rows 4 to 6. I want to know the number only if the column elements at the same index prior to it are smaller than 3.

For example:

At row 4 the number 1 is at the 3rd position, but there exists a value 3 in row 1 at the same position in a previous row. Thus this should be neglected and proceed to find the next.

At row 6, the condition fails, and it should be returned.

Upvotes: 1

Views: 848

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

How about

C = sum( A(4:6,all(A(1:6,:)<3,1)) == 1, 2)

The part B = A(4:6,all(A(1:6,:)<3,1)) extracts rows 4 through 6 and applies the <3 limit on all columns, from row 1 to 6. Then, equating B == 1 and summing over the rows will result in

C = [0
     0
     1];

Upvotes: 2

Related Questions