Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of the first row of a matrix that satisfies two conditions in APL Language?

One more question to learn how to use APL Language. Suppose you have an array, as an example:

c1 c2 c3 c4 c5 c6
3 123 0 4 5 6
3 134 0 2 3 4
3 231 180 1 2 5
4 121 0 3 2 4
4 124 120 4 6 3
4 222 222 5 3 5

So, how to find out which row has a value of 4 in the 1st column and a value grather than 0 in the 3rd column?

The expected answer is 5th line, in the just 5

like image 923
Rodrigo Miranda Avatar asked Apr 02 '21 05:04

Rodrigo Miranda


1 Answers

When you want to make such "queries", think Boolean masks.

      table ← 6 6⍴3 123 0 4 5 6 3 134 0 2 3 4 3 231 180 1 2 5 4 121 0 3 2 4 4 124 120 4 6 3 4 222 222 5 

Let's extract the first column:

      table[;1]
3 3 3 4 4 4

And indicate which elements have a value of 4:

      table[;1] = 4
0 0 0 1 1 1

Similarly, we can indicate which elements of column 3 have value greater than 0:

      table[;3] > 0
0 0 1 0 1 1

Their intersection (logical AND) indicates all rows that fulfil your criteria:

      (table[;1] = 4) ∧ (table[;3] > 0)
0 0 0 0 1 1

The index of the first 1 is the row number for the first row that fulfils your criteria:

      ((table[;1] = 4) ∧ (table[;3] > 0)) ⍳ 1
5

Try it online!

Alternatively, we can use the final mask to filter the table and obtain all rows that fulfil your criteria:

      ((table[;1] = 4) ∧ (table[;3] > 0)) ⌿ table
4 124 120 4 6 3
4 222 222 5 3 5

Try it online!

Or we can generate all the row numbers:

      ⍳ 1 ↑ ⍴ table
1 2 3 4 5 6

Then use our Boolean mask to filter that, finding the row numbers of all the rows that fulfil your criteria:

      ((table[;1] = 4) ∧ (table[;3] > 0)) ⌿ ⍳ 1 ↑ ⍴ table
5 6

Try it online!

like image 164
Adám Avatar answered Nov 14 '22 08:11

Adám