简体   繁体   English

用J动词“ I”替换数组中的项。

[英]Replace items in an array with J verb `I.`

Here is a simple replace for a rank-1 list using the I. verb: 这是使用I.动词的1级列表的简单替换:

y=: _3 _2 _1 1 2 3
0 (I. y<0) } y

The result is 结果是

0 0 0 1 2 3

How do I do such a replacement for a rank-2 matrix? 我该如何替换等级2矩阵?

For example, 例如,

y2 =: 2 3 $ _3 _2 _1 1 2 3
0 (I. y2<0) } y2

I got (J806) 我拿到了(J806)

|index error
|   0    (I.y2<2)}y2

The reason seems to be 原因似乎是

(I. y2 < 0)

gives

0 1 2
0 0 0

which isn't taken well by } . }不能很好地解决这个问题。

The simplest answer for this problem is to use dyadic >. 这个问题的最简单答案是使用dyadic >. ( Larger of ) ... 较大 )...

   0 >. y2
0 0 0
1 2 3

If you want to use a more general conditional replacement criteria, then the following form may be useful: 如果要使用更通用的条件替换条件,则以下表格可能会有用:

   (0 > y2)} y2 ,: 0
0 0 0
1 2 3

If you want it as a verb then you can use the gerund form (v1`v2)} y ↔ (v1 y)} (v2 y) : 如果希望将其用作动词,则可以使用动名词形式(v1`v2)} y ↔ (v1 y)} (v2 y)

   (0 > ])`(0 ,:~ ])} y2
0 0 0
1 2 3

If your question is more about scatter index replacement then that is possible too. 如果您的问题是关于散布索引替换的,那么这也是可能的。 You need to get the 2D indices of positions you want to replace, for example: 您需要获取要替换位置的2D索引,例如:

   4 $. $. 0 > y2
0 0
0 1
0 2

Now box those indices and use dyadic } : 现在将这些索引装箱并使用dyadic }

   0 (<"1 (4 $. $. 0 > y2)) } y2
0 0 0
1 2 3

Again you can turn this into a verb using a gerund left argument to dyadic } ( x (v0`v1`v2)} y ↔ (x v0 y) (x v1 y)} (x v2 y) ) like this: 同样,您可以使用二元对}x (v0`v1`v2)} y ↔ (x v0 y) (x v1 y)} (x v2 y)的gerund left参数将其变成动词,如下所示:

   0  [`([: (<"1) 4 $. [: $. 0 > ])`]} y2
0 0 0
1 2 3

Or 要么

   100 101 102  [`([: (<"1) 4 $. [: $. 0 > ])`]} y2
100 101 102
  1   2   3

To tidy this up a bit you could define getIdx as separate verb... 为了弄清楚这一点,您可以将getIdx定义为单独的动词...

   getIdx=: 4 $. $.
   0 [`([: <"1@getIdx 0 > ])`]} y2
0 0 0
1 2 3

This is not a good solution. 这不是一个好的解决方案。 My original approach was to change the rank of the test so that it looks at each row separately, but that does not work in the general case (see comments below). 我最初的方法是更改​​测试的排名,以便分别查看每一行,但这在一般情况下不起作用(请参阅下面的评论)。

 [y2 =: 2 3 $ _3 _2 _1 1 2 3  
_3 _2 _1
 1  2  3


   I. y2<0
0 1 2
0 0 0


   0 (I. y2<0)"1 } y2  NB. Rank of 1 applies to each row of y2
0 0 0
1 2 3

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

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