j

How to define selection using index function in J


Let's assume I have a following tensor t:

   ]m=: 100 + 4 4 $ i.16
100 101 102 103
104 105 106 107
108 109 110 111
112 113 114 115
   ]t=: (m ,: m+100) , m+200
100 101 102 103
104 105 106 107
108 109 110 111
112 113 114 115

200 201 202 203
204 205 206 207
208 209 210 211
212 213 214 215

300 301 302 303
304 305 306 307
308 309 310 311
312 313 314 315

I would like to select diagonal plane of it, so :

100 105 110 115

200 205 210 215

300 305 310 315

How to define function that acts on indices? (and here have for any plane index let's choose ix(row) = ix (column)) Also, how to define functions working on values and indices together? So I would be interested in having something like this:

(f t) { t

Thanks!


Solution

  • You can convert an array of values to its corresponding array of indices with (#:i.)@$ m

    To get an example f „working on values and indices together“ you can then plug it in as a dyad that takes values on the left and indices on the right:

      f=.(2|[) +. ([:=/"1]) NB. odd value or diagonal index
      ]r=.([ f (#:i.)@$) m  NB. values f indices
    1 1 0 1
    0 1 0 1
    0 1 1 1
    0 1 0 1
      r #&, m               NB. flatten lists & get values where bit is set
    100 101 103 105 107 109 110 111 113 115
    

    Everything wrapped into an adverb that can be applied f:

      sel=.1 : '#~&, [ u (#:i.)@$`
      f sel m
    100 101 103 105 107 109 110 111 113 115