简体   繁体   English

在 J 中使用向量/矩阵时打印值及其相关索引

[英]Print values and it's associated index when working with vectors / matrix in J

If I want to check how many values in a vector or matrix are less than a given value I can use +/ (a < 20).如果我想检查向量或矩阵中有多少值小于给定值,我可以使用 +/ (a < 20)。 But what if I wanted to know both the specific value and it's index.但是,如果我想知道具体值和它的索引怎么办。 Something like (2(value) 5(index)) as a table.像 (2(value) 5(index)) 这样的表格。 I looked at i., i: (which give first and last position) and I. Does sorting first help?我看着 i., i: (给出第一个和最后一个位置)和 I. 先排序有帮助吗?

A very common pattern in J is the creation of a mask from a filter and applying an action on and/or using the masked data in a hook or fork: J 中一个非常常见的模式是从过滤器创建一个掩码,并在钩子或叉子中应用和/或使用掩码数据:

((actions) (filter)) (data)

For example:例如:

NB. Random array
a =: ? 20 $ 10
6 3 9 0 3 3 0 6 2 9 2 4 6 8 7 4 6 1 7 1

NB. Filter and mask
f =: 5 < ]
m =: f a
1 0 1 0 0 0 0 1 0 1 0 0 1 1 1 0 1 0 1 0

NB. Values of a on m
m # a
6 9 6 9 6 8 7 6 7

NB. Indices of a on m
I. m
0 2 7 9 12 13 14 16 18

NB. Joint results
(I.m) ,: (m # a)
0 2 7 9 12 13 14 16 18
6 9 6 9  6  8  7  6  7

In other words, in this case you have m&# and f acting on a and I. acting on m .换句话说,在这种情况下,您有m&#f作用于aI.作用于m Notice that the final result can be derived from an action on m alone by commuting the arguments of copy #~ :请注意,最终结果可以通过对副本#~的 arguments 进行交换,仅从对m的操作得出:

(I. ,: (a #~ ]) m
0 2 7 9 12 13 14 16 18
6 9 6 9  6  8  7  6  7

and a can be pulled out from the action on m like so:并且可以从对m的操作中拉出a ,如下所示:

a ( (]I.) ,: (#~ ])) m

But since m itself is derived from an action ( f ) on a , we can write:但是由于m本身是从 a 上的动作 ( f ) 派生a ,我们可以这样写:

a ( (]I.) ,: (#~ ])) (f a)

which is a simple monadic hook yv (fy)(vf) y .这是一个简单的单子钩子yv (fy)(vf) y

Therefore:所以:

action =: (]I.) ,: (#~ ])
filter =: 5 < ]
data =: a

(action filter) data
0 2 7 9 12 13 14 16 18
6 9 6 9  6  8  7  6  7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM